diff --git a/.github/workflows/dart.yml b/.github/workflows/dart.yml index 970b7fdf8..22a0116ec 100644 --- a/.github/workflows/dart.yml +++ b/.github/workflows/dart.yml @@ -39,23 +39,23 @@ jobs: - name: mono_repo self validate run: dart pub global run mono_repo generate --validate job_002: - name: "format_analyze; linux; Dart 3.6.0; PKG: protobuf; `dart analyze lib`, `dart analyze test`" + name: "format_analyze; linux; Dart 3.7.0; PKG: protobuf; `dart analyze lib`, `dart analyze test`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:protobuf;commands:analyze_1-analyze_2" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0;packages:protobuf;commands:analyze_1-analyze_2" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:protobuf - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0 + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0;packages:protobuf + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0 os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.7.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -191,23 +191,23 @@ jobs: if: "always() && steps.protoc_plugin_pub_upgrade.conclusion == 'success'" working-directory: protoc_plugin job_006: - name: "run_tests; linux; Dart 3.6.0; PKG: protobuf; `dart test`" + name: "run_tests; linux; Dart 3.7.0; PKG: protobuf; `dart test`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:protobuf;commands:test" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0;packages:protobuf;commands:test" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:protobuf - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0 + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0;packages:protobuf + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0 os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.7.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -227,23 +227,23 @@ jobs: - job_004 - job_005 job_007: - name: "run_tests; linux; Dart 3.6.0; PKG: protoc_plugin; `./../tool/setup.sh`, `make protos`, `dart test`" + name: "run_tests; linux; Dart 3.7.0; PKG: protoc_plugin; `./../tool/setup.sh`, `make protos`, `dart test`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:protoc_plugin;commands:command_0-command_2-test" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0;packages:protoc_plugin;commands:command_0-command_2-test" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:protoc_plugin - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0 + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0;packages:protoc_plugin + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0 os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.7.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -351,23 +351,23 @@ jobs: - job_004 - job_005 job_010: - name: "run_tests; osx; Dart 3.6.0; PKG: protobuf; `dart test`" + name: "run_tests; osx; Dart 3.7.0; PKG: protobuf; `dart test`" runs-on: macos-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 with: path: "~/.pub-cache/hosted" - key: "os:macos-latest;pub-cache-hosted;sdk:3.6.0;packages:protobuf;commands:test" + key: "os:macos-latest;pub-cache-hosted;sdk:3.7.0;packages:protobuf;commands:test" restore-keys: | - os:macos-latest;pub-cache-hosted;sdk:3.6.0;packages:protobuf - os:macos-latest;pub-cache-hosted;sdk:3.6.0 + os:macos-latest;pub-cache-hosted;sdk:3.7.0;packages:protobuf + os:macos-latest;pub-cache-hosted;sdk:3.7.0 os:macos-latest;pub-cache-hosted os:macos-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.7.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -423,13 +423,13 @@ jobs: - job_004 - job_005 job_012: - name: "run_tests; windows; Dart 3.6.0; PKG: protobuf; `dart test`" + name: "run_tests; windows; Dart 3.7.0; PKG: protobuf; `dart test`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.7.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 diff --git a/benchmarks/bin/deep_copy.dart b/benchmarks/bin/deep_copy.dart index 6f37c260c..09372b672 100644 --- a/benchmarks/bin/deep_copy.dart +++ b/benchmarks/bin/deep_copy.dart @@ -15,11 +15,14 @@ class Benchmark extends BenchmarkBase { final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), - _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), - _message2 = GoogleMessage2.fromBuffer(message2Input); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), + _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), + _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { @@ -33,12 +36,17 @@ class Benchmark extends BenchmarkBase { } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( - 'deep_copy', message1Proto2Input, message1Proto3Input, message2Input) - .report(); + 'deep_copy', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/from_binary.dart b/benchmarks/bin/from_binary.dart index 5f6630c7d..71604a298 100644 --- a/benchmarks/bin/from_binary.dart +++ b/benchmarks/bin/from_binary.dart @@ -17,11 +17,14 @@ class Benchmark extends BenchmarkBase { final Uint8List _message1Proto3Input; final Uint8List _message2Input; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2Input = Uint8List.fromList(message1Proto2Input), - _message1Proto3Input = Uint8List.fromList(message1Proto3Input), - _message2Input = Uint8List.fromList(message2Input); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2Input = Uint8List.fromList(message1Proto2Input), + _message1Proto3Input = Uint8List.fromList(message1Proto3Input), + _message2Input = Uint8List.fromList(message2Input); @override void run() { @@ -32,12 +35,17 @@ class Benchmark extends BenchmarkBase { } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); - Benchmark('from_binary', message1Proto2Input, message1Proto3Input, - message2Input) - .report(); + Benchmark( + 'from_binary', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/from_json_string.dart b/benchmarks/bin/from_json_string.dart index 9475617e4..67ec2dd00 100644 --- a/benchmarks/bin/from_json_string.dart +++ b/benchmarks/bin/from_json_string.dart @@ -15,14 +15,17 @@ class Benchmark extends BenchmarkBase { final String _message1Proto3JsonString; final String _message2JsonString; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2JsonString = - p2.GoogleMessage1.fromBuffer(message1Proto2Input).writeToJson(), - _message1Proto3JsonString = - p3.GoogleMessage1.fromBuffer(message1Proto3Input).writeToJson(), - _message2JsonString = - GoogleMessage2.fromBuffer(message2Input).writeToJson(); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2JsonString = + p2.GoogleMessage1.fromBuffer(message1Proto2Input).writeToJson(), + _message1Proto3JsonString = + p3.GoogleMessage1.fromBuffer(message1Proto3Input).writeToJson(), + _message2JsonString = + GoogleMessage2.fromBuffer(message2Input).writeToJson(); @override void run() { @@ -33,12 +36,17 @@ class Benchmark extends BenchmarkBase { } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); - Benchmark('from_json_string', message1Proto2Input, message1Proto3Input, - message2Input) - .report(); + Benchmark( + 'from_json_string', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/from_proto3_json_object.dart b/benchmarks/bin/from_proto3_json_object.dart index fe67b00a4..7c30875af 100644 --- a/benchmarks/bin/from_proto3_json_object.dart +++ b/benchmarks/bin/from_proto3_json_object.dart @@ -15,32 +15,42 @@ class Benchmark extends BenchmarkBase { final Object? _message1Proto3Proto3JsonObject; final Object? _message2Proto3JsonObject; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2Proto3JsonObject = - p2.GoogleMessage1.fromBuffer(message1Proto2Input).toProto3Json(), - _message1Proto3Proto3JsonObject = - p3.GoogleMessage1.fromBuffer(message1Proto3Input).toProto3Json(), - _message2Proto3JsonObject = - GoogleMessage2.fromBuffer(message2Input).toProto3Json(); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2Proto3JsonObject = + p2.GoogleMessage1.fromBuffer(message1Proto2Input).toProto3Json(), + _message1Proto3Proto3JsonObject = + p3.GoogleMessage1.fromBuffer(message1Proto3Input).toProto3Json(), + _message2Proto3JsonObject = + GoogleMessage2.fromBuffer(message2Input).toProto3Json(); @override void run() { - p2.GoogleMessage1.create() - .mergeFromProto3Json(_message1Proto2Proto3JsonObject); - p3.GoogleMessage1.create() - .mergeFromProto3Json(_message1Proto3Proto3JsonObject); + p2.GoogleMessage1.create().mergeFromProto3Json( + _message1Proto2Proto3JsonObject, + ); + p3.GoogleMessage1.create().mergeFromProto3Json( + _message1Proto3Proto3JsonObject, + ); GoogleMessage2.create().mergeFromProto3Json(_message2Proto3JsonObject); } } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); - Benchmark('from_proto3_json_object', message1Proto2Input, message1Proto3Input, - message2Input) - .report(); + Benchmark( + 'from_proto3_json_object', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/from_proto3_json_string.dart b/benchmarks/bin/from_proto3_json_string.dart index 1e6852186..a8b83b7ce 100644 --- a/benchmarks/bin/from_proto3_json_string.dart +++ b/benchmarks/bin/from_proto3_json_string.dart @@ -17,33 +17,47 @@ class Benchmark extends BenchmarkBase { final String _message1Proto3Proto3JsonString; final String _message2Proto3JsonString; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2Proto3JsonString = jsonEncode( - p2.GoogleMessage1.fromBuffer(message1Proto2Input).toProto3Json()), - _message1Proto3Proto3JsonString = jsonEncode( - p3.GoogleMessage1.fromBuffer(message1Proto3Input).toProto3Json()), - _message2Proto3JsonString = - jsonEncode(GoogleMessage2.fromBuffer(message2Input).toProto3Json()); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2Proto3JsonString = jsonEncode( + p2.GoogleMessage1.fromBuffer(message1Proto2Input).toProto3Json(), + ), + _message1Proto3Proto3JsonString = jsonEncode( + p3.GoogleMessage1.fromBuffer(message1Proto3Input).toProto3Json(), + ), + _message2Proto3JsonString = jsonEncode( + GoogleMessage2.fromBuffer(message2Input).toProto3Json(), + ); @override void run() { - p2.GoogleMessage1.create() - .mergeFromProto3Json(jsonDecode(_message1Proto2Proto3JsonString)); - p3.GoogleMessage1.create() - .mergeFromProto3Json(jsonDecode(_message1Proto3Proto3JsonString)); - GoogleMessage2.create() - .mergeFromProto3Json(jsonDecode(_message2Proto3JsonString)); + p2.GoogleMessage1.create().mergeFromProto3Json( + jsonDecode(_message1Proto2Proto3JsonString), + ); + p3.GoogleMessage1.create().mergeFromProto3Json( + jsonDecode(_message1Proto3Proto3JsonString), + ); + GoogleMessage2.create().mergeFromProto3Json( + jsonDecode(_message2Proto3JsonString), + ); } } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); - Benchmark('from_proto3_json_string', message1Proto2Input, message1Proto3Input, - message2Input) - .report(); + Benchmark( + 'from_proto3_json_string', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/hash_code.dart b/benchmarks/bin/hash_code.dart index c90c13166..b2465f4f9 100644 --- a/benchmarks/bin/hash_code.dart +++ b/benchmarks/bin/hash_code.dart @@ -15,11 +15,14 @@ class Benchmark extends BenchmarkBase { final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), - _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), - _message2 = GoogleMessage2.fromBuffer(message2Input); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), + _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), + _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { @@ -30,12 +33,17 @@ class Benchmark extends BenchmarkBase { } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( - 'hash_code', message1Proto2Input, message1Proto3Input, message2Input) - .report(); + 'hash_code', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/query_decode_json.dart b/benchmarks/bin/query_decode_json.dart index c66fbee49..0db0a135f 100644 --- a/benchmarks/bin/query_decode_json.dart +++ b/benchmarks/bin/query_decode_json.dart @@ -10,7 +10,7 @@ class Benchmark extends BenchmarkBase { final String _input; Benchmark(super.name, List input) - : _input = f0.A0.fromBuffer(input).writeToJson(); + : _input = f0.A0.fromBuffer(input).writeToJson(); @override void run() { diff --git a/benchmarks/bin/query_set_nested_value.dart b/benchmarks/bin/query_set_nested_value.dart index 9b9adc335..4cfb46d6e 100644 --- a/benchmarks/bin/query_set_nested_value.dart +++ b/benchmarks/bin/query_set_nested_value.dart @@ -13,15 +13,16 @@ class Benchmark extends BenchmarkBase { final f0.A0 _input; Benchmark(super.name, List input) - : _input = f0.A0.fromBuffer(input)..freeze(); + : _input = f0.A0.fromBuffer(input)..freeze(); @override void run() { // ignore: unused_result _input.rebuild((f0.A0 a0Builder) { a0Builder.a4.last = a0Builder.a4.last.rebuild((f2.A1 a1builder) { - a1builder.a378 = a1builder.a378 - .rebuild((f19.A220 a220builder) => a220builder.a234 = 'new_value'); + a1builder.a378 = a1builder.a378.rebuild( + (f19.A220 a220builder) => a220builder.a234 = 'new_value', + ); }); }); } diff --git a/benchmarks/bin/repeated_field.dart b/benchmarks/bin/repeated_field.dart index 4580b4432..2aa42c2ae 100644 --- a/benchmarks/bin/repeated_field.dart +++ b/benchmarks/bin/repeated_field.dart @@ -13,7 +13,7 @@ class RepeatedBenchmark extends BenchmarkBase { final Uint8List _buffer; RepeatedBenchmark(super.name, GoogleMessage2 message) - : _buffer = message.writeToBuffer(); + : _buffer = message.writeToBuffer(); @override void run() => GoogleMessage2.fromBuffer(_buffer); @@ -23,7 +23,7 @@ class RepeatedEnumBenchmark extends BenchmarkBase { final Uint8List _buffer; RepeatedEnumBenchmark(super.name, f12.A58 message) - : _buffer = message.writeToBuffer(); + : _buffer = message.writeToBuffer(); @override void run() => f12.A58.fromBuffer(_buffer); diff --git a/benchmarks/bin/to_binary.dart b/benchmarks/bin/to_binary.dart index e725f012f..214e7b4b5 100644 --- a/benchmarks/bin/to_binary.dart +++ b/benchmarks/bin/to_binary.dart @@ -15,11 +15,14 @@ class Benchmark extends BenchmarkBase { final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), - _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), - _message2 = GoogleMessage2.fromBuffer(message2Input); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), + _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), + _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { @@ -30,12 +33,17 @@ class Benchmark extends BenchmarkBase { } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( - 'to_binary', message1Proto2Input, message1Proto3Input, message2Input) - .report(); + 'to_binary', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/to_json_string.dart b/benchmarks/bin/to_json_string.dart index 2c482da17..4d7ba9e7c 100644 --- a/benchmarks/bin/to_json_string.dart +++ b/benchmarks/bin/to_json_string.dart @@ -15,11 +15,14 @@ class Benchmark extends BenchmarkBase { final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), - _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), - _message2 = GoogleMessage2.fromBuffer(message2Input); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), + _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), + _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { @@ -30,12 +33,17 @@ class Benchmark extends BenchmarkBase { } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); - Benchmark('to_json_string', message1Proto2Input, message1Proto3Input, - message2Input) - .report(); + Benchmark( + 'to_json_string', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/to_proto3_json_object.dart b/benchmarks/bin/to_proto3_json_object.dart index cb6ff6d43..806f5d6be 100644 --- a/benchmarks/bin/to_proto3_json_object.dart +++ b/benchmarks/bin/to_proto3_json_object.dart @@ -15,11 +15,14 @@ class Benchmark extends BenchmarkBase { final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), - _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), - _message2 = GoogleMessage2.fromBuffer(message2Input); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), + _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), + _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { @@ -30,12 +33,17 @@ class Benchmark extends BenchmarkBase { } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); - Benchmark('to_proto3_json_object', message1Proto2Input, message1Proto3Input, - message2Input) - .report(); + Benchmark( + 'to_proto3_json_object', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/bin/to_proto3_json_string.dart b/benchmarks/bin/to_proto3_json_string.dart index ac61e1390..689c0b056 100644 --- a/benchmarks/bin/to_proto3_json_string.dart +++ b/benchmarks/bin/to_proto3_json_string.dart @@ -17,11 +17,14 @@ class Benchmark extends BenchmarkBase { final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; - Benchmark(super.name, List message1Proto2Input, - List message1Proto3Input, List message2Input) - : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), - _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), - _message2 = GoogleMessage2.fromBuffer(message2Input); + Benchmark( + super.name, + List message1Proto2Input, + List message1Proto3Input, + List message2Input, + ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), + _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), + _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { @@ -32,12 +35,17 @@ class Benchmark extends BenchmarkBase { } void main() { - final List message1Proto2Input = - readfile('datasets/google_message1_proto2.pb'); - final List message1Proto3Input = - readfile('datasets/google_message1_proto3.pb'); + final List message1Proto2Input = readfile( + 'datasets/google_message1_proto2.pb', + ); + final List message1Proto3Input = readfile( + 'datasets/google_message1_proto3.pb', + ); final List message2Input = readfile('datasets/google_message2.pb'); - Benchmark('to_proto3_json_string', message1Proto2Input, message1Proto3Input, - message2Input) - .report(); + Benchmark( + 'to_proto3_json_string', + message1Proto2Input, + message1Proto3Input, + message2Input, + ).report(); } diff --git a/benchmarks/lib/readfile.dart b/benchmarks/lib/readfile.dart index c5723f4a0..b182a3b87 100644 --- a/benchmarks/lib/readfile.dart +++ b/benchmarks/lib/readfile.dart @@ -2,5 +2,6 @@ // 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. -export 'readfile_vm.dart' if (dart.library.js_interop) 'readfile_js.dart' +export 'readfile_vm.dart' + if (dart.library.js_interop) 'readfile_js.dart' show readfile; diff --git a/benchmarks/pubspec.yaml b/benchmarks/pubspec.yaml index 2c1bc0d44..330d27f48 100644 --- a/benchmarks/pubspec.yaml +++ b/benchmarks/pubspec.yaml @@ -7,7 +7,7 @@ description: Benchmarks for various protobuf functions. publish_to: none environment: - sdk: ^3.6.0 + sdk: ^3.7.0 resolution: workspace diff --git a/benchmarks/tool/compile_benchmarks.dart b/benchmarks/tool/compile_benchmarks.dart index e454d33dd..443dc890c 100755 --- a/benchmarks/tool/compile_benchmarks.dart +++ b/benchmarks/tool/compile_benchmarks.dart @@ -12,10 +12,14 @@ import 'package:path/path.dart' as path; import 'package:pool/pool.dart' show Pool; Future main(List args) async { - final argParser = ArgParser() - ..addOption('target', - mandatory: false, defaultsTo: 'aot,exe,jit,js,js-production') - ..addOption('jobs', abbr: 'j', mandatory: false); + final argParser = + ArgParser() + ..addOption( + 'target', + mandatory: false, + defaultsTo: 'aot,exe,jit,js,js-production', + ) + ..addOption('jobs', abbr: 'j', mandatory: false); final parsedArgs = argParser.parse(args); @@ -52,8 +56,10 @@ Future main(List args) async { break; default: - print('Unsupported target: $targetStr. Supported targets: aot, exe, ' - 'jit, js, js-production, wasm, wasm-omit-checks'); + print( + 'Unsupported target: $targetStr. Supported targets: aot, exe, ' + 'jit, js, js-production, wasm, wasm-omit-checks', + ); exit(1); } } @@ -62,11 +68,12 @@ Future main(List args) async { if (sourceFiles.isEmpty) { // Compile all files in bin/ - sourceFiles = Directory('bin') - .listSync(recursive: false) - .where((dirFile) => path.extension(dirFile.path) == '.dart') - .map((dirFile) => dirFile.path) - .toList(); + sourceFiles = + Directory('bin') + .listSync(recursive: false) + .where((dirFile) => path.extension(dirFile.path) == '.dart') + .map((dirFile) => dirFile.path) + .toList(); } final commands = >[]; @@ -88,8 +95,9 @@ Future main(List args) async { final pool = Pool(jobs); - final stream = pool.forEach, CompileProcess>(commands, - (List command) async { + final stream = pool.forEach, CompileProcess>(commands, ( + List command, + ) async { final commandStr = command.join(' '); print(commandStr); final result = await Process.run(command[0], command.sublist(1)); @@ -102,13 +110,16 @@ Future main(List args) async { print('Process exited with $exitCode'); print('Command: ${compileProcess.command}'); print( - 'Process stdout ---------------------------------------------------'); + 'Process stdout ---------------------------------------------------', + ); print(compileProcess.result.stdout); print( - 'Process stderr ---------------------------------------------------'); + 'Process stderr ---------------------------------------------------', + ); print(compileProcess.result.stderr); print( - '------------------------------------------------------------------'); + '------------------------------------------------------------------', + ); exit(1); } } @@ -155,7 +166,7 @@ List aotProcessArgs(String sourceFile) { 'aot-snapshot', sourceFile, '-o', - 'out/$baseNameNoExt.aot' + 'out/$baseNameNoExt.aot', ]; } @@ -172,7 +183,7 @@ List jitProcessArgs(String sourceFile) { 'dart', '--snapshot-kind=kernel', '--snapshot=out/$baseNameNoExt.dill', - sourceFile + sourceFile, ]; } @@ -192,7 +203,7 @@ List jsProductionProcessArgs(String sourceFile) { sourceFile, '-O4', '-o', - 'out/$baseNameNoExt.production.js' + 'out/$baseNameNoExt.production.js', ]; } @@ -206,6 +217,6 @@ List wasmProcessArgs(String sourceFile) { sourceFile, '-O4', '-o', - 'out/$baseNameNoExt.wasm' + 'out/$baseNameNoExt.wasm', ]; } diff --git a/protobuf/CHANGELOG.md b/protobuf/CHANGELOG.md index 61f11ba0e..d0580b297 100644 --- a/protobuf/CHANGELOG.md +++ b/protobuf/CHANGELOG.md @@ -1,3 +1,9 @@ +## 4.1.1-wip + +* Minimum SDK dependency bumped from 3.6.0 to 3.7.0. ([#1024]) + +[#1024]: https://github.com/google/protobuf.dart/pull/1024 + ## 4.1.0 * Improve packed field decoding performance. ([#959], [#981]) diff --git a/protobuf/lib/meta.dart b/protobuf/lib/meta.dart index 826cb614d..8a9ba6815 100644 --- a/protobuf/lib/meta.dart +++ b/protobuf/lib/meta.dart @@ -90,5 +90,5 @@ const ProtobufEnum_reservedNames = [ 'hashCode', 'noSuchMethod', 'runtimeType', - 'toString' + 'toString', ]; diff --git a/protobuf/lib/src/protobuf/builder_info.dart b/protobuf/lib/src/protobuf/builder_info.dart index 1ae344133..4ac8bc06e 100644 --- a/protobuf/lib/src/protobuf/builder_info.dart +++ b/protobuf/lib/src/protobuf/builder_info.dart @@ -43,71 +43,105 @@ class BuilderInfo { // For well-known types. final Object? Function(GeneratedMessage message, TypeRegistry typeRegistry)? - toProto3Json; - final Function(GeneratedMessage targetMessage, Object json, - TypeRegistry typeRegistry, JsonParsingContext context)? fromProto3Json; + toProto3Json; + final Function( + GeneratedMessage targetMessage, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + )? + fromProto3Json; final CreateBuilderFunc? createEmptyInstance; - BuilderInfo(String? messageName, - {PackageName package = const PackageName(''), - this.createEmptyInstance, - this.toProto3Json, - this.fromProto3Json}) - : qualifiedMessageName = '${package.prefix}$messageName'; + BuilderInfo( + String? messageName, { + PackageName package = const PackageName(''), + this.createEmptyInstance, + this.toProto3Json, + this.fromProto3Json, + }) : qualifiedMessageName = '${package.prefix}$messageName'; void add( - int tagNumber, - String name, - int? fieldType, - dynamic defaultOrMaker, - CreateBuilderFunc? subBuilder, - ValueOfFunc? valueOf, - List? enumValues, - {String? protoName}) { + int tagNumber, + String name, + int? fieldType, + dynamic defaultOrMaker, + CreateBuilderFunc? subBuilder, + ValueOfFunc? valueOf, + List? enumValues, { + String? protoName, + }) { final index = byIndex.length; - final fieldInfo = (tagNumber == 0) - ? FieldInfo.dummy(index) - : FieldInfo(name, tagNumber, index, fieldType!, - defaultOrMaker: defaultOrMaker, - subBuilder: subBuilder, - valueOf: valueOf, - enumValues: enumValues, - protoName: protoName); + final fieldInfo = + (tagNumber == 0) + ? FieldInfo.dummy(index) + : FieldInfo( + name, + tagNumber, + index, + fieldType!, + defaultOrMaker: defaultOrMaker, + subBuilder: subBuilder, + valueOf: valueOf, + enumValues: enumValues, + protoName: protoName, + ); _addField(fieldInfo); } void addMapField( - int tagNumber, - String name, - int keyFieldType, - int valueFieldType, - BuilderInfo mapEntryBuilderInfo, - CreateBuilderFunc? valueCreator, - {ProtobufEnum? defaultEnumValue, - String? protoName}) { + int tagNumber, + String name, + int keyFieldType, + int valueFieldType, + BuilderInfo mapEntryBuilderInfo, + CreateBuilderFunc? valueCreator, { + ProtobufEnum? defaultEnumValue, + String? protoName, + }) { final index = byIndex.length; - _addField(MapFieldInfo(name, tagNumber, index, PbFieldType.M, - keyFieldType, valueFieldType, mapEntryBuilderInfo, valueCreator, - defaultEnumValue: defaultEnumValue, protoName: protoName)); + _addField( + MapFieldInfo( + name, + tagNumber, + index, + PbFieldType.M, + keyFieldType, + valueFieldType, + mapEntryBuilderInfo, + valueCreator, + defaultEnumValue: defaultEnumValue, + protoName: protoName, + ), + ); } void addRepeated( - int tagNumber, - String name, - int fieldType, - CheckFunc check, - CreateBuilderFunc? subBuilder, - ValueOfFunc? valueOf, - List? enumValues, - {ProtobufEnum? defaultEnumValue, - String? protoName}) { + int tagNumber, + String name, + int fieldType, + CheckFunc check, + CreateBuilderFunc? subBuilder, + ValueOfFunc? valueOf, + List? enumValues, { + ProtobufEnum? defaultEnumValue, + String? protoName, + }) { final index = byIndex.length; - _addField(FieldInfo.repeated( - name, tagNumber, index, fieldType, check, subBuilder, + _addField( + FieldInfo.repeated( + name, + tagNumber, + index, + fieldType, + check, + subBuilder, valueOf: valueOf, enumValues: enumValues, defaultEnumValue: defaultEnumValue, - protoName: protoName)); + protoName: protoName, + ), + ); } void _addField(FieldInfo fi) { @@ -123,105 +157,195 @@ class BuilderInfo { } } - void a(int tagNumber, String name, int fieldType, - {dynamic defaultOrMaker, - CreateBuilderFunc? subBuilder, - ValueOfFunc? valueOf, - List? enumValues, - String? protoName}) { - add(tagNumber, name, fieldType, defaultOrMaker, subBuilder, valueOf, - enumValues, - protoName: protoName); + void a( + int tagNumber, + String name, + int fieldType, { + dynamic defaultOrMaker, + CreateBuilderFunc? subBuilder, + ValueOfFunc? valueOf, + List? enumValues, + String? protoName, + }) { + add( + tagNumber, + name, + fieldType, + defaultOrMaker, + subBuilder, + valueOf, + enumValues, + protoName: protoName, + ); } /// Adds PbFieldType.OS String with no default value to reduce generated /// code size. void aOS(int tagNumber, String name, {String? protoName}) { - add(tagNumber, name, PbFieldType.OS, null, null, null, null, - protoName: protoName); + add( + tagNumber, + name, + PbFieldType.OS, + null, + null, + null, + null, + protoName: protoName, + ); } /// Adds PbFieldType.PS String with no default value. void pPS(int tagNumber, String name, {String? protoName}) { - addRepeated(tagNumber, name, PbFieldType.PS, - getCheckFunction(PbFieldType.PS), null, null, null, - protoName: protoName); + addRepeated( + tagNumber, + name, + PbFieldType.PS, + getCheckFunction(PbFieldType.PS), + null, + null, + null, + protoName: protoName, + ); } /// Adds PbFieldType.QS String with no default value. void aQS(int tagNumber, String name, {String? protoName}) { - add(tagNumber, name, PbFieldType.QS, null, null, null, null, - protoName: protoName); + add( + tagNumber, + name, + PbFieldType.QS, + null, + null, + null, + null, + protoName: protoName, + ); } /// Adds Int64 field with Int64.ZERO default. void aInt64(int tagNumber, String name, {String? protoName}) { - add(tagNumber, name, PbFieldType.O6, Int64.ZERO, null, null, null, - protoName: protoName); + add( + tagNumber, + name, + PbFieldType.O6, + Int64.ZERO, + null, + null, + null, + protoName: protoName, + ); } /// Adds a boolean with no default value. void aOB(int tagNumber, String name, {String? protoName}) { - add(tagNumber, name, PbFieldType.OB, null, null, null, null, - protoName: protoName); + add( + tagNumber, + name, + PbFieldType.OB, + null, + null, + null, + null, + protoName: protoName, + ); } // Enum. - void e(int tagNumber, String name, int fieldType, - {dynamic defaultOrMaker, - ValueOfFunc? valueOf, - List? enumValues, - String? protoName}) { + void e( + int tagNumber, + String name, + int fieldType, { + dynamic defaultOrMaker, + ValueOfFunc? valueOf, + List? enumValues, + String? protoName, + }) { add( - tagNumber, name, fieldType, defaultOrMaker, null, valueOf, enumValues, - protoName: protoName); + tagNumber, + name, + fieldType, + defaultOrMaker, + null, + valueOf, + enumValues, + protoName: protoName, + ); } // Repeated, not a message, group, or enum. void p(int tagNumber, String name, int fieldType, {String? protoName}) { assert(!_isGroupOrMessage(fieldType) && !_isEnum(fieldType)); - addRepeated(tagNumber, name, fieldType, getCheckFunction(fieldType), - null, null, null, - protoName: protoName); + addRepeated( + tagNumber, + name, + fieldType, + getCheckFunction(fieldType), + null, + null, + null, + protoName: protoName, + ); } // Repeated message, group, or enum. - void pc(int tagNumber, String name, int fieldType, - {CreateBuilderFunc? subBuilder, - ValueOfFunc? valueOf, - List? enumValues, - ProtobufEnum? defaultEnumValue, - String? protoName}) { + void pc( + int tagNumber, + String name, + int fieldType, { + CreateBuilderFunc? subBuilder, + ValueOfFunc? valueOf, + List? enumValues, + ProtobufEnum? defaultEnumValue, + String? protoName, + }) { assert(_isGroupOrMessage(fieldType) || _isEnum(fieldType)); - addRepeated(tagNumber, name, fieldType, _checkNotNull, subBuilder, - valueOf, enumValues, - defaultEnumValue: defaultEnumValue, protoName: protoName); + addRepeated( + tagNumber, + name, + fieldType, + _checkNotNull, + subBuilder, + valueOf, + enumValues, + defaultEnumValue: defaultEnumValue, + protoName: protoName, + ); } - void aOM(int tagNumber, String name, - {required T Function() subBuilder, String? protoName}) { + void aOM( + int tagNumber, + String name, { + required T Function() subBuilder, + String? protoName, + }) { add( - tagNumber, - name, - PbFieldType.OM, - GeneratedMessage._defaultMakerFor(subBuilder), - subBuilder, - null, - null, - protoName: protoName); + tagNumber, + name, + PbFieldType.OM, + GeneratedMessage._defaultMakerFor(subBuilder), + subBuilder, + null, + null, + protoName: protoName, + ); } - void aQM(int tagNumber, String name, - {required T Function() subBuilder, String? protoName}) { + void aQM( + int tagNumber, + String name, { + required T Function() subBuilder, + String? protoName, + }) { add( - tagNumber, - name, - PbFieldType.QM, - GeneratedMessage._defaultMakerFor(subBuilder), - subBuilder, - null, - null, - protoName: protoName); + tagNumber, + name, + PbFieldType.QM, + GeneratedMessage._defaultMakerFor(subBuilder), + subBuilder, + null, + null, + protoName: protoName, + ); } // oneof declarations. @@ -232,26 +356,51 @@ class BuilderInfo { } // Map field. - void m(int tagNumber, String name, - {String? entryClassName, - required int keyFieldType, - required int valueFieldType, - CreateBuilderFunc? valueCreator, - ValueOfFunc? valueOf, - List? enumValues, - ProtobufEnum? defaultEnumValue, - PackageName packageName = const PackageName(''), - String? protoName, - dynamic valueDefaultOrMaker}) { - final mapEntryBuilderInfo = BuilderInfo(entryClassName, - package: packageName) - ..add(PbMap._keyFieldNumber, 'key', keyFieldType, null, null, null, null) - ..add(PbMap._valueFieldNumber, 'value', valueFieldType, - valueDefaultOrMaker, valueCreator, valueOf, enumValues); - - addMapField(tagNumber, name, keyFieldType, valueFieldType, - mapEntryBuilderInfo, valueCreator, - defaultEnumValue: defaultEnumValue, protoName: protoName); + void m( + int tagNumber, + String name, { + String? entryClassName, + required int keyFieldType, + required int valueFieldType, + CreateBuilderFunc? valueCreator, + ValueOfFunc? valueOf, + List? enumValues, + ProtobufEnum? defaultEnumValue, + PackageName packageName = const PackageName(''), + String? protoName, + dynamic valueDefaultOrMaker, + }) { + final mapEntryBuilderInfo = + BuilderInfo(entryClassName, package: packageName) + ..add( + PbMap._keyFieldNumber, + 'key', + keyFieldType, + null, + null, + null, + null, + ) + ..add( + PbMap._valueFieldNumber, + 'value', + valueFieldType, + valueDefaultOrMaker, + valueCreator, + valueOf, + enumValues, + ); + + addMapField( + tagNumber, + name, + keyFieldType, + valueFieldType, + mapEntryBuilderInfo, + valueCreator, + defaultEnumValue: defaultEnumValue, + protoName: protoName, + ); } bool containsTagNumber(int tagNumber) => fieldInfo.containsKey(tagNumber); @@ -304,25 +453,30 @@ class BuilderInfo { } List _computeSortedByTag() => - // Code generator inserts fields in tag order, but it's possible for - // user-written code to insert unordered. - List.from(fieldInfo.values, growable: false) - ..sort( - (FieldInfo a, FieldInfo b) => a.tagNumber.compareTo(b.tagNumber)); + // Code generator inserts fields in tag order, but it's possible for + // user-written code to insert unordered. + List.from(fieldInfo.values, growable: false) + ..sort((FieldInfo a, FieldInfo b) => a.tagNumber.compareTo(b.tagNumber)); GeneratedMessage _makeEmptyMessage( - int tagNumber, ExtensionRegistry? extensionRegistry) { + int tagNumber, + ExtensionRegistry? extensionRegistry, + ) { var subBuilderFunc = subBuilder(tagNumber); if (subBuilderFunc == null && extensionRegistry != null) { - subBuilderFunc = extensionRegistry - .getExtension(qualifiedMessageName, tagNumber)! - .subBuilder; + subBuilderFunc = + extensionRegistry + .getExtension(qualifiedMessageName, tagNumber)! + .subBuilder; } return subBuilderFunc!(); } ProtobufEnum? _decodeEnum( - int tagNumber, ExtensionRegistry? registry, int rawValue) { + int tagNumber, + ExtensionRegistry? registry, + int rawValue, + ) { final f = valueOfFunc(tagNumber); if (f != null) { return f(rawValue); diff --git a/protobuf/lib/src/protobuf/coded_buffer.dart b/protobuf/lib/src/protobuf/coded_buffer.dart index 463b22b5b..4166228c4 100644 --- a/protobuf/lib/src/protobuf/coded_buffer.dart +++ b/protobuf/lib/src/protobuf/coded_buffer.dart @@ -29,8 +29,12 @@ void _writeToCodedBufferWriter(_FieldSet fs, CodedBufferWriter out) { } } -void _mergeFromCodedBufferReader(BuilderInfo meta, _FieldSet fs, - CodedBufferReader input, ExtensionRegistry registry) { +void _mergeFromCodedBufferReader( + BuilderInfo meta, + _FieldSet fs, + CodedBufferReader input, + ExtensionRegistry registry, +) { fs._ensureWritable(); while (true) { final tag = input.readTag(); @@ -193,7 +197,14 @@ void _mergeFromCodedBufferReader(BuilderInfo meta, _FieldSet fs, case PbFieldType._REPEATED_ENUM: final list = fs._ensureRepeatedField(meta, fi); _readPackableToListEnum( - list, meta, fs, input, wireType, tagNumber, registry); + list, + meta, + fs, + input, + wireType, + tagNumber, + registry, + ); break; case PbFieldType._REPEATED_GROUP: final subMessage = meta._makeEmptyMessage(tagNumber, registry); @@ -391,13 +402,14 @@ void _mergeFromCodedBufferReader(BuilderInfo meta, _FieldSet fs, } void _readPackableToListEnum( - List list, - BuilderInfo meta, - _FieldSet fs, - CodedBufferReader input, - int wireType, - int tagNumber, - ExtensionRegistry registry) { + List list, + BuilderInfo meta, + _FieldSet fs, + CodedBufferReader input, + int wireType, + int tagNumber, + ExtensionRegistry registry, +) { if (wireType == WIRETYPE_LENGTH_DELIMITED) { // Packed. input._withLimit(input.readInt32(), () { @@ -411,8 +423,14 @@ void _readPackableToListEnum( } } -void _readRepeatedEnum(List list, BuilderInfo meta, _FieldSet fs, - CodedBufferReader input, int tagNumber, ExtensionRegistry registry) { +void _readRepeatedEnum( + List list, + BuilderInfo meta, + _FieldSet fs, + CodedBufferReader input, + int tagNumber, + ExtensionRegistry registry, +) { final rawValue = input.readEnum(); final value = meta._decodeEnum(tagNumber, registry, rawValue); if (value == null) { diff --git a/protobuf/lib/src/protobuf/coded_buffer_reader.dart b/protobuf/lib/src/protobuf/coded_buffer_reader.dart index e03e4c2c5..2bb9c2ecd 100644 --- a/protobuf/lib/src/protobuf/coded_buffer_reader.dart +++ b/protobuf/lib/src/protobuf/coded_buffer_reader.dart @@ -25,19 +25,22 @@ class CodedBufferReader { final int _recursionLimit; final int _sizeLimit; - CodedBufferReader(List buffer, - {int recursionLimit = DEFAULT_RECURSION_LIMIT, - int sizeLimit = DEFAULT_SIZE_LIMIT}) - : _buffer = buffer is Uint8List ? buffer : Uint8List.fromList(buffer), - _recursionLimit = recursionLimit, - _sizeLimit = math.min(sizeLimit, buffer.length) { + CodedBufferReader( + List buffer, { + int recursionLimit = DEFAULT_RECURSION_LIMIT, + int sizeLimit = DEFAULT_SIZE_LIMIT, + }) : _buffer = buffer is Uint8List ? buffer : Uint8List.fromList(buffer), + _recursionLimit = recursionLimit, + _sizeLimit = math.min(sizeLimit, buffer.length) { _currentLimit = _sizeLimit; } void _throwTruncatedMessageError(int limit) { if (limit > _sizeLimit && limit <= _buffer.length) { throw InvalidProtocolBufferException.truncatedMessageDueToSizeLimit( - _buffer.length, _sizeLimit); + _buffer.length, + _sizeLimit, + ); } throw InvalidProtocolBufferException.truncatedMessage(); } @@ -59,8 +62,9 @@ class CodedBufferReader { void _withLimit(int byteLimit, Function() callback) { if (byteLimit < 0) { throw ArgumentError( - 'CodedBufferReader encountered an embedded string or message' - ' which claimed to have negative size.'); + 'CodedBufferReader encountered an embedded string or message' + ' which claimed to have negative size.', + ); } byteLimit += _bufferPos; final oldLimit = _currentLimit; @@ -82,8 +86,11 @@ class CodedBufferReader { } } - void readGroup(int fieldNumber, GeneratedMessage message, - ExtensionRegistry extensionRegistry) { + void readGroup( + int fieldNumber, + GeneratedMessage message, + ExtensionRegistry extensionRegistry, + ) { if (_recursionDepth >= _recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } @@ -106,15 +113,18 @@ class CodedBufferReader { } void readMessage( - GeneratedMessage message, ExtensionRegistry extensionRegistry) { + GeneratedMessage message, + ExtensionRegistry extensionRegistry, + ) { final length = readInt32(); if (_recursionDepth >= _recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } if (length < 0) { throw ArgumentError( - 'CodedBufferReader encountered an embedded string or message' - ' which claimed to have negative size.'); + 'CodedBufferReader encountered an embedded string or message' + ' which claimed to have negative size.', + ); } final oldLimit = _currentLimit; @@ -205,7 +215,10 @@ class CodedBufferReader { final length = readInt32(); _checkLimit(length); return Uint8List.view( - _buffer.buffer, _buffer.offsetInBytes + _bufferPos - length, length); + _buffer.buffer, + _buffer.offsetInBytes + _bufferPos - length, + length, + ); } @pragma('vm:prefer-inline') @@ -214,8 +227,9 @@ class CodedBufferReader { final length = readInt32(); final stringPos = _bufferPos; _checkLimit(length); - return const Utf8Decoder(allowMalformed: true) - .convert(_buffer, stringPos, stringPos + length); + return const Utf8Decoder( + allowMalformed: true, + ).convert(_buffer, stringPos, stringPos + length); } @pragma('vm:prefer-inline') diff --git a/protobuf/lib/src/protobuf/coded_buffer_writer.dart b/protobuf/lib/src/protobuf/coded_buffer_writer.dart index 700c46305..a8dffd80a 100644 --- a/protobuf/lib/src/protobuf/coded_buffer_writer.dart +++ b/protobuf/lib/src/protobuf/coded_buffer_writer.dart @@ -89,9 +89,17 @@ class CodedBufferWriter { _writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); final mark = _startLengthDelimited(); _writeValue( - PbMap._keyFieldNumber, map.keyFieldType, key, keyWireFormat); - _writeValue(PbMap._valueFieldNumber, map.valueFieldType, value, - valueWireFormat); + PbMap._keyFieldNumber, + map.keyFieldType, + key, + keyWireFormat, + ); + _writeValue( + PbMap._valueFieldNumber, + map.valueFieldType, + value, + valueWireFormat, + ); _endLengthDelimited(mark); }); return; @@ -153,7 +161,11 @@ class CodedBufferWriter { final bytesToCopyFromChunk = leftInChunk > bytesToCopy ? bytesToCopy : leftInChunk; buffer.setRange( - outPos, outPos + bytesToCopyFromChunk, chunk, chunkPos); + outPos, + outPos + bytesToCopyFromChunk, + chunk, + chunkPos, + ); chunkPos += bytesToCopyFromChunk; outPos += bytesToCopyFromChunk; bytesToCopy -= bytesToCopyFromChunk; @@ -325,8 +337,11 @@ class CodedBufferWriter { void _writeInt32(int value) { const sizeInBytes = 4; _ensureBytes(sizeInBytes); - _outputChunkAsByteData! - .setInt32(_bytesInChunk, value & 0xFFFFFFFF, Endian.little); + _outputChunkAsByteData!.setInt32( + _bytesInChunk, + value & 0xFFFFFFFF, + Endian.little, + ); _bytesInChunk += sizeInBytes; _bytesTotal += sizeInBytes; } @@ -437,7 +452,11 @@ class CodedBufferWriter { } void _writeValue( - int fieldNumber, int valueType, dynamic value, int wireFormat) { + int fieldNumber, + int valueType, + dynamic value, + int wireFormat, + ) { _writeTag(fieldNumber, wireFormat); _writeValueAs(valueType, value); if (valueType == PbFieldType._GROUP_BIT) { @@ -488,25 +507,26 @@ class CodedBufferWriter { static const _MESSAGE_BIT_INDEX = 20; /// Mapping from value types to wire-types indexed by _valueTypeIndex(...). - static final Uint8List _wireTypes = Uint8List(32) - ..[_BOOL_BIT_INDEX] = WIRETYPE_VARINT - ..[_BYTES_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED - ..[_STRING_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED - ..[_DOUBLE_BIT_INDEX] = WIRETYPE_FIXED64 - ..[_FLOAT_BIT_INDEX] = WIRETYPE_FIXED32 - ..[_ENUM_BIT_INDEX] = WIRETYPE_VARINT - ..[_GROUP_BIT_INDEX] = WIRETYPE_START_GROUP - ..[_INT32_BIT_INDEX] = WIRETYPE_VARINT - ..[_INT64_BIT_INDEX] = WIRETYPE_VARINT - ..[_SINT32_BIT_INDEX] = WIRETYPE_VARINT - ..[_SINT64_BIT_INDEX] = WIRETYPE_VARINT - ..[_UINT32_BIT_INDEX] = WIRETYPE_VARINT - ..[_UINT64_BIT_INDEX] = WIRETYPE_VARINT - ..[_FIXED32_BIT_INDEX] = WIRETYPE_FIXED32 - ..[_FIXED64_BIT_INDEX] = WIRETYPE_FIXED64 - ..[_SFIXED32_BIT_INDEX] = WIRETYPE_FIXED32 - ..[_SFIXED64_BIT_INDEX] = WIRETYPE_FIXED64 - ..[_MESSAGE_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED; + static final Uint8List _wireTypes = + Uint8List(32) + ..[_BOOL_BIT_INDEX] = WIRETYPE_VARINT + ..[_BYTES_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED + ..[_STRING_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED + ..[_DOUBLE_BIT_INDEX] = WIRETYPE_FIXED64 + ..[_FLOAT_BIT_INDEX] = WIRETYPE_FIXED32 + ..[_ENUM_BIT_INDEX] = WIRETYPE_VARINT + ..[_GROUP_BIT_INDEX] = WIRETYPE_START_GROUP + ..[_INT32_BIT_INDEX] = WIRETYPE_VARINT + ..[_INT64_BIT_INDEX] = WIRETYPE_VARINT + ..[_SINT32_BIT_INDEX] = WIRETYPE_VARINT + ..[_SINT64_BIT_INDEX] = WIRETYPE_VARINT + ..[_UINT32_BIT_INDEX] = WIRETYPE_VARINT + ..[_UINT64_BIT_INDEX] = WIRETYPE_VARINT + ..[_FIXED32_BIT_INDEX] = WIRETYPE_FIXED32 + ..[_FIXED64_BIT_INDEX] = WIRETYPE_FIXED64 + ..[_SFIXED32_BIT_INDEX] = WIRETYPE_FIXED32 + ..[_SFIXED64_BIT_INDEX] = WIRETYPE_FIXED64 + ..[_MESSAGE_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED; } int _encodeZigZag32(int value) => (value << 1) ^ (value >> 31); diff --git a/protobuf/lib/src/protobuf/exceptions.dart b/protobuf/lib/src/protobuf/exceptions.dart index ae629f5b7..3effb4486 100644 --- a/protobuf/lib/src/protobuf/exceptions.dart +++ b/protobuf/lib/src/protobuf/exceptions.dart @@ -21,35 +21,38 @@ class InvalidProtocolBufferException implements Exception { String toString() => 'InvalidProtocolBufferException: $message'; InvalidProtocolBufferException.invalidEndTag() - : this._('Protocol message end-group tag did not match expected tag.'); + : this._('Protocol message end-group tag did not match expected tag.'); InvalidProtocolBufferException.invalidTag() - : this._('Protocol message contained an invalid tag (zero).'); + : this._('Protocol message contained an invalid tag (zero).'); InvalidProtocolBufferException.invalidWireType() - : this._('Protocol message tag had invalid wire type.'); + : this._('Protocol message tag had invalid wire type.'); InvalidProtocolBufferException.malformedVarint() - : this._('CodedBufferReader encountered a malformed varint.'); + : this._('CodedBufferReader encountered a malformed varint.'); - InvalidProtocolBufferException.recursionLimitExceeded() : this._(''' + InvalidProtocolBufferException.recursionLimitExceeded() + : this._(''' Protocol message had too many levels of nesting. May be malicious. Use CodedBufferReader.setRecursionLimit() to increase the depth limit. '''); InvalidProtocolBufferException.truncatedMessage() - : this._(_truncatedMessageText); + : this._(_truncatedMessageText); InvalidProtocolBufferException.truncatedMessageDueToSizeLimit( - int originalSize, int truncatedSize) - : this._('''$_truncatedMessageText + int originalSize, + int truncatedSize, + ) : this._('''$_truncatedMessageText Note that the buffer containing the message has $originalSize bytes, but CodedBufferReader was allowed to parse only $truncatedSize bytes. '''); InvalidProtocolBufferException.wrongAnyMessage( - String anyTypeName, unpackerTypeName) - : this._(''' + String anyTypeName, + unpackerTypeName, + ) : this._(''' The type of the Any message ($anyTypeName) does not match the given unpacker ($unpackerTypeName). '''); diff --git a/protobuf/lib/src/protobuf/extension.dart b/protobuf/lib/src/protobuf/extension.dart index 1144443fc..27743b727 100644 --- a/protobuf/lib/src/protobuf/extension.dart +++ b/protobuf/lib/src/protobuf/extension.dart @@ -8,27 +8,49 @@ part of '../../protobuf.dart'; class Extension extends FieldInfo { final String extendee; - Extension(this.extendee, String name, int tagNumber, int fieldType, - {dynamic defaultOrMaker, - CreateBuilderFunc? subBuilder, - ValueOfFunc? valueOf, - List? enumValues, - String? protoName}) - : super(name, tagNumber, null, fieldType, - defaultOrMaker: defaultOrMaker, - subBuilder: subBuilder, - valueOf: valueOf, - enumValues: enumValues, - protoName: protoName); + Extension( + this.extendee, + String name, + int tagNumber, + int fieldType, { + dynamic defaultOrMaker, + CreateBuilderFunc? subBuilder, + ValueOfFunc? valueOf, + List? enumValues, + String? protoName, + }) : super( + name, + tagNumber, + null, + fieldType, + defaultOrMaker: defaultOrMaker, + subBuilder: subBuilder, + valueOf: valueOf, + enumValues: enumValues, + protoName: protoName, + ); - Extension.repeated(this.extendee, String name, int tagNumber, int fieldType, - {required CheckFunc check, - CreateBuilderFunc? subBuilder, - ValueOfFunc? valueOf, - List? enumValues, - String? protoName}) - : super.repeated(name, tagNumber, null, fieldType, check, subBuilder, - valueOf: valueOf, enumValues: enumValues, protoName: protoName); + Extension.repeated( + this.extendee, + String name, + int tagNumber, + int fieldType, { + required CheckFunc check, + CreateBuilderFunc? subBuilder, + ValueOfFunc? valueOf, + List? enumValues, + String? protoName, + }) : super.repeated( + name, + tagNumber, + null, + fieldType, + check, + subBuilder, + valueOf: valueOf, + enumValues: enumValues, + protoName: protoName, + ); @override int get hashCode => extendee.hashCode * 31 + tagNumber; diff --git a/protobuf/lib/src/protobuf/extension_field_set.dart b/protobuf/lib/src/protobuf/extension_field_set.dart index 9e9b5b010..9e0664359 100644 --- a/protobuf/lib/src/protobuf/extension_field_set.dart +++ b/protobuf/lib/src/protobuf/extension_field_set.dart @@ -87,11 +87,17 @@ class _ExtensionFieldSet { final fi = _getInfoOrNull(tagNumber); if (fi == null) { throw ArgumentError( - 'tag $tagNumber not defined in $_parent._messageName'); + 'tag $tagNumber not defined in $_parent._messageName', + ); } if (fi.isRepeated) { - throw ArgumentError(_parent._setFieldFailedMessage( - fi, value, 'repeating field (use get + .add())')); + throw ArgumentError( + _parent._setFieldFailedMessage( + fi, + value, + 'repeating field (use get + .add())', + ), + ); } _ensureWritable(); _parent._validateField(fi, value); @@ -103,8 +109,13 @@ class _ExtensionFieldSet { void _setFieldAndInfo(Extension fi, value) { _ensureWritable(); if (fi.isRepeated) { - throw ArgumentError(_parent._setFieldFailedMessage( - fi, value, 'repeating field (use get + .add())')); + throw ArgumentError( + _parent._setFieldFailedMessage( + fi, + value, + 'repeating field (use get + .add())', + ), + ); } _ensureWritable(); _validateInfo(fi); @@ -122,7 +133,8 @@ class _ExtensionFieldSet { void _validateInfo(Extension fi) { if (fi.extendee != _parent._messageName) { throw ArgumentError( - 'Extension $fi not legal for message ${_parent._messageName}'); + 'Extension $fi not legal for message ${_parent._messageName}', + ); } } @@ -193,9 +205,10 @@ class _ExtensionFieldSet { final unknownFields = _parent._unknownFields; if (unknownFields != null && unknownFields.hasField(extension.tagNumber)) { throw StateError( - 'Trying to get $extension that is present as an unknown field. ' - 'Parse the message with this extension in the extension registry or ' - 'use `ExtensionRegistry.reparseMessage`.'); + 'Trying to get $extension that is present as an unknown field. ' + 'Parse the message with this extension in the extension registry or ' + 'use `ExtensionRegistry.reparseMessage`.', + ); } } } diff --git a/protobuf/lib/src/protobuf/extension_registry.dart b/protobuf/lib/src/protobuf/extension_registry.dart index 997992732..bc2f8b468 100644 --- a/protobuf/lib/src/protobuf/extension_registry.dart +++ b/protobuf/lib/src/protobuf/extension_registry.dart @@ -15,8 +15,10 @@ class ExtensionRegistry { /// Stores an [extension] in the registry. void add(Extension extension) { - final map = - _extensions.putIfAbsent(extension.extendee, () => {}); + final map = _extensions.putIfAbsent( + extension.extendee, + () => {}, + ); map[extension.tagNumber] = extension; } @@ -87,7 +89,9 @@ class ExtensionRegistry { } T _reparseMessage( - T message, ExtensionRegistry extensionRegistry) { + T message, + ExtensionRegistry extensionRegistry, +) { T? result; T ensureResult() { if (result == null) { @@ -116,7 +120,9 @@ T _reparseMessage( final typeId = group._fields[_messageSetItemTypeIdTag]!.varints[0].toInt(); if (extensionRegistry.getExtension( - message.info_.qualifiedMessageName, typeId) == + message.info_.qualifiedMessageName, + typeId, + ) == null) { unparsedItemList.addGroup(group); } else { @@ -135,12 +141,12 @@ T _reparseMessage( } else { extensionRegistry._extensions[message.info_.qualifiedMessageName] ?.forEach((tagNumber, extension) { - final unknownField = messageUnknownFields._fields[tagNumber]; - if (unknownField != null) { - unknownField.writeTo(tagNumber, codedBufferWriter); - ensureUnknownFields()._fields.remove(tagNumber); - } - }); + final unknownField = messageUnknownFields._fields[tagNumber]; + if (unknownField != null) { + unknownField.writeTo(tagNumber, codedBufferWriter); + ensureUnknownFields()._fields.remove(tagNumber); + } + }); } final buffer = codedBufferWriter.toBuffer(); @@ -187,8 +193,10 @@ T _reparseMessage( } else if (field.isGroupOrMessage) { final messageSubField = message._fieldSet._values[field.index!]; if (messageSubField == null) continue; - final reparsedSubField = - _reparseMessage(messageSubField, extensionRegistry); + final reparsedSubField = _reparseMessage( + messageSubField, + extensionRegistry, + ); if (!identical(messageSubField, reparsedSubField)) { ensureResult()._fieldSet._values[field.index!] = reparsedSubField; } diff --git a/protobuf/lib/src/protobuf/field_info.dart b/protobuf/lib/src/protobuf/field_info.dart index 8f46fb61d..a30925e26 100644 --- a/protobuf/lib/src/protobuf/field_info.dart +++ b/protobuf/lib/src/protobuf/field_info.dart @@ -98,42 +98,54 @@ class FieldInfo { /// Only available in repeated fields. final CheckFunc? check; - FieldInfo(this.name, this.tagNumber, this.index, this.type, - {dynamic defaultOrMaker, - this.subBuilder, - this.valueOf, - this.enumValues, - this.defaultEnumValue, - String? protoName}) - : makeDefault = findMakeDefault(type, defaultOrMaker), - check = null, - _protoName = protoName, - assert(type != 0), - assert(!_isGroupOrMessage(type) || - subBuilder != null || - _isMapField(type)), - assert(!_isEnum(type) || valueOf != null); + FieldInfo( + this.name, + this.tagNumber, + this.index, + this.type, { + dynamic defaultOrMaker, + this.subBuilder, + this.valueOf, + this.enumValues, + this.defaultEnumValue, + String? protoName, + }) : makeDefault = findMakeDefault(type, defaultOrMaker), + check = null, + _protoName = protoName, + assert(type != 0), + assert( + !_isGroupOrMessage(type) || subBuilder != null || _isMapField(type), + ), + assert(!_isEnum(type) || valueOf != null); // Represents a field that has been removed by a program transformation. FieldInfo.dummy(this.index) - : name = '', - _protoName = '', - tagNumber = 0, - type = 0, - makeDefault = null, - valueOf = null, - check = null, - enumValues = null, - defaultEnumValue = null, - subBuilder = null; - - FieldInfo.repeated(this.name, this.tagNumber, this.index, this.type, - CheckFunc this.check, this.subBuilder, - {this.valueOf, this.enumValues, this.defaultEnumValue, String? protoName}) - : makeDefault = (() => PbList(check: check)), - _protoName = protoName, - assert(_isRepeated(type)), - assert(!_isEnum(type) || valueOf != null); + : name = '', + _protoName = '', + tagNumber = 0, + type = 0, + makeDefault = null, + valueOf = null, + check = null, + enumValues = null, + defaultEnumValue = null, + subBuilder = null; + + FieldInfo.repeated( + this.name, + this.tagNumber, + this.index, + this.type, + CheckFunc this.check, + this.subBuilder, { + this.valueOf, + this.enumValues, + this.defaultEnumValue, + String? protoName, + }) : makeDefault = (() => PbList(check: check)), + _protoName = protoName, + assert(_isRepeated(type)), + assert(!_isEnum(type) || valueOf != null); static MakeDefaultFunc? findMakeDefault(int type, dynamic defaultOrMaker) { if (defaultOrMaker == null) return PbFieldType._defaultForType(type); @@ -204,8 +216,10 @@ class FieldInfo { // Recurse on each item in the list. var position = 0; for (final message in list) { - message._fieldSet - ._appendInvalidFields(problems, '$prefix$name[$position].'); + message._fieldSet._appendInvalidFields( + problems, + '$prefix$name[$position].', + ); position++; } } @@ -237,7 +251,9 @@ final RegExp _upperCase = RegExp('[A-Z]'); String _unCamelCase(String name) { return name.replaceAllMapped( - _upperCase, (match) => '_${match.group(0)!.toLowerCase()}'); + _upperCase, + (match) => '_${match.group(0)!.toLowerCase()}', + ); } /// A [FieldInfo] subclass for protobuf `map` fields. @@ -262,21 +278,26 @@ class MapFieldInfo extends FieldInfo?> { final BuilderInfo mapEntryBuilderInfo; MapFieldInfo( - String name, - int tagNumber, - int index, - int type, - this.keyFieldType, - this.valueFieldType, - this.mapEntryBuilderInfo, - this.valueCreator, - {ProtobufEnum? defaultEnumValue, - String? protoName}) - : assert(_isMapField(type)), - super(name, tagNumber, index, type, - defaultOrMaker: () => PbMap(keyFieldType, valueFieldType), - defaultEnumValue: defaultEnumValue, - protoName: protoName) { + String name, + int tagNumber, + int index, + int type, + this.keyFieldType, + this.valueFieldType, + this.mapEntryBuilderInfo, + this.valueCreator, { + ProtobufEnum? defaultEnumValue, + String? protoName, + }) : assert(_isMapField(type)), + super( + name, + tagNumber, + index, + type, + defaultOrMaker: () => PbMap(keyFieldType, valueFieldType), + defaultEnumValue: defaultEnumValue, + protoName: protoName, + ) { assert(!_isEnum(type) || valueOf != null); } diff --git a/protobuf/lib/src/protobuf/field_set.dart b/protobuf/lib/src/protobuf/field_set.dart index 8e8732dcc..ec73665b0 100644 --- a/protobuf/lib/src/protobuf/field_set.dart +++ b/protobuf/lib/src/protobuf/field_set.dart @@ -6,14 +6,18 @@ part of '../../protobuf.dart'; @pragma('vm:never-inline') @pragma('wasm:never-inline') -void _throwFrozenMessageModificationError(String messageName, - [String? methodName]) { +void _throwFrozenMessageModificationError( + String messageName, [ + String? methodName, +]) { if (methodName != null) { throw UnsupportedError( - 'Attempted to call $methodName on a read-only message ($messageName)'); + 'Attempted to call $methodName on a read-only message ($messageName)', + ); } throw UnsupportedError( - 'Attempted to change a read-only message ($messageName)'); + 'Attempted to change a read-only message ($messageName)', + ); } /// All the data in a [GeneratedMessage]. @@ -79,8 +83,8 @@ class _FieldSet { final Map? _oneofCases; _FieldSet(this._message, BuilderInfo meta) - : _values = _makeValueList(meta.byIndex.length), - _oneofCases = meta.oneofs.isEmpty ? null : {}; + : _values = _makeValueList(meta.byIndex.length), + _oneofCases = meta.oneofs.isEmpty ? null : {}; static List _makeValueList(int length) { if (length == 0) return _zeroList; @@ -272,8 +276,9 @@ class _FieldSet { } if (fi.isRepeated) { - throw ArgumentError(_setFieldFailedMessage( - fi, value, 'repeating field (use get + .add())')); + throw ArgumentError( + _setFieldFailedMessage(fi, value, 'repeating field (use get + .add())'), + ); } _validateField(fi, value); _setNonExtensionFieldUnchecked(meta, fi, value); @@ -629,10 +634,15 @@ class _FieldSet { hash = _HashUtils._combine(hash, value.hashCode); } else if (fi.isRepeated) { final PbList list = value; - hash = _HashUtils._combine(hash, _HashUtils._hashObjects(list.map((enm) { - final ProtobufEnum enm_ = enm; - return enm_.value; - }))); + hash = _HashUtils._combine( + hash, + _HashUtils._hashObjects( + list.map((enm) { + final ProtobufEnum enm_ = enm; + return enm_.value; + }), + ), + ); } else { final ProtobufEnum enm = value; hash = _HashUtils._combine(hash, enm.value); @@ -670,17 +680,22 @@ class _FieldSet { } for (final fi in _infosSortedByTag) { - writeFieldValue(_values[fi.index!], - fi.name == '' ? fi.tagNumber.toString() : fi.name); + writeFieldValue( + _values[fi.index!], + fi.name == '' ? fi.tagNumber.toString() : fi.name, + ); } final extensions = _extensions; if (extensions != null) { extensions._info.keys.toList() ..sort() - ..forEach((int tagNumber) => writeFieldValue( + ..forEach( + (int tagNumber) => writeFieldValue( _extensions!._values[tagNumber], - '[${_extensions!._info[tagNumber]!.name}]')); + '[${_extensions!._info[tagNumber]!.name}]', + ), + ); } final unknownFields = _unknownFields; @@ -728,10 +743,12 @@ class _FieldSet { final otherUnknownJsonData = other._unknownJsonData; if (otherUnknownJsonData != null) { - final newUnknownJsonData = - Map.from(_unknownJsonData ?? {}); - otherUnknownJsonData - .forEach((key, value) => newUnknownJsonData[key] = value); + final newUnknownJsonData = Map.from( + _unknownJsonData ?? {}, + ); + otherUnknownJsonData.forEach( + (key, value) => newUnknownJsonData[key] = value, + ); _unknownJsonData = newUnknownJsonData.isEmpty ? null : newUnknownJsonData; } } @@ -783,9 +800,10 @@ class _FieldSet { } if (otherFi.isGroupOrMessage) { - final currentFi = isExtension - ? _ensureExtensions()._getFieldOrNull(fi as Extension) - : _values[fi.index!]; + final currentFi = + isExtension + ? _ensureExtensions()._getFieldOrNull(fi as Extension) + : _values[fi.index!]; final GeneratedMessage msg = fieldValue; if (currentFi == null) { @@ -797,8 +815,10 @@ class _FieldSet { } if (isExtension) { - _ensureExtensions() - ._setFieldAndInfo(fi as Extension, fieldValue); + _ensureExtensions()._setFieldAndInfo( + fi as Extension, + fieldValue, + ); } else { _validateField(fi, fieldValue); _setNonExtensionFieldUnchecked(meta, fi, fieldValue); @@ -868,8 +888,8 @@ class _FieldSet { if (fieldInfo.isMapField) { final PbMap? map = _values[index]; if (map != null) { - _values[index] = (fieldInfo as MapFieldInfo)._createMapField() - ..addAll(map); + _values[index] = + (fieldInfo as MapFieldInfo)._createMapField()..addAll(map); } } else if (fieldInfo.isRepeated) { final PbList? list = _values[index]; diff --git a/protobuf/lib/src/protobuf/generated_message.dart b/protobuf/lib/src/protobuf/generated_message.dart index fe8765139..7cf6a0a11 100644 --- a/protobuf/lib/src/protobuf/generated_message.dart +++ b/protobuf/lib/src/protobuf/generated_message.dart @@ -49,9 +49,11 @@ abstract class GeneratedMessage { /// Creates a deep copy of the fields in this message. /// (The generated code uses [mergeFromMessage].) - @Deprecated('Using this can add significant size overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @Deprecated( + 'Using this can add significant size overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version', + ) GeneratedMessage clone(); /// Creates an empty instance of the same message type as this. @@ -99,9 +101,11 @@ abstract class GeneratedMessage { /// /// Makes a writable shallow copy of this message, applies the [updates] to /// it, and marks the copy read-only before returning it. - @Deprecated('Using this can add significant size overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') + @Deprecated( + 'Using this can add significant size overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version', + ) GeneratedMessage copyWith(void Function(GeneratedMessage) updates) { final builder = toBuilder(); updates(builder); @@ -188,8 +192,10 @@ abstract class GeneratedMessage { _writeToCodedBufferWriter(_fieldSet, output); /// Same as [mergeFromBuffer], but takes a [CodedBufferReader] input. - void mergeFromCodedBufferReader(CodedBufferReader input, - [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { + void mergeFromCodedBufferReader( + CodedBufferReader input, [ + ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, + ]) { final meta = _fieldSet._meta; _mergeFromCodedBufferReader(meta, _fieldSet, input, extensionRegistry); } @@ -202,8 +208,10 @@ abstract class GeneratedMessage { /// * Else, if it's a scalar, this overwrites our field. /// * Else, (it's a non-repeated sub-message), this recursively merges into /// the existing sub-message. - void mergeFromBuffer(List input, - [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { + void mergeFromBuffer( + List input, [ + ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, + ]) { final codedInput = CodedBufferReader(input); final meta = _fieldSet._meta; _mergeFromCodedBufferReader(meta, _fieldSet, codedInput, extensionRegistry); @@ -256,9 +264,9 @@ abstract class GeneratedMessage { /// /// Unknown field data, data for which there is no metadata for the associated /// field, will not be included. - Object? toProto3Json( - {TypeRegistry typeRegistry = const TypeRegistry.empty()}) => - _writeToProto3Json(_fieldSet, typeRegistry); + Object? toProto3Json({ + TypeRegistry typeRegistry = const TypeRegistry.empty(), + }) => _writeToProto3Json(_fieldSet, typeRegistry); /// Merges field values from [json], a JSON object using proto3 encoding. /// @@ -287,26 +295,37 @@ abstract class GeneratedMessage { /// /// Throws [FormatException] if the JSON not formatted correctly (a String /// where a number was expected etc.). - void mergeFromProto3Json(Object? json, - {TypeRegistry typeRegistry = const TypeRegistry.empty(), - bool ignoreUnknownFields = false, - bool supportNamesWithUnderscores = true, - bool permissiveEnums = false}) => - _mergeFromProto3Json(json, _fieldSet, typeRegistry, ignoreUnknownFields, - supportNamesWithUnderscores, permissiveEnums); + void mergeFromProto3Json( + Object? json, { + TypeRegistry typeRegistry = const TypeRegistry.empty(), + bool ignoreUnknownFields = false, + bool supportNamesWithUnderscores = true, + bool permissiveEnums = false, + }) => _mergeFromProto3Json( + json, + _fieldSet, + typeRegistry, + ignoreUnknownFields, + supportNamesWithUnderscores, + permissiveEnums, + ); /// Merges field values from [data], a JSON object, encoded as described by /// [GeneratedMessage.writeToJson]. /// /// For the proto3 JSON format use: [mergeFromProto3Json]. - void mergeFromJson(String data, - [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { + void mergeFromJson( + String data, [ + ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, + ]) { /// Disable lazy creation of Dart objects for a dart2js speedup. /// This is a slight regression on the Dart VM. /// TODO(skybrian) we could skip the reviver if we're running /// on the Dart VM for a slight speedup. - final Map jsonMap = - jsonDecode(data, reviver: _emptyReviver); + final Map jsonMap = jsonDecode( + data, + reviver: _emptyReviver, + ); _mergeFromJsonMap(_fieldSet, jsonMap, extensionRegistry); } @@ -315,8 +334,10 @@ abstract class GeneratedMessage { /// Merges field values from a JSON object represented as a Dart map. /// /// The encoding is described in [GeneratedMessage.writeToJson]. - void mergeFromJsonMap(Map json, - [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { + void mergeFromJsonMap( + Map json, [ + ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, + ]) { _mergeFromJsonMap(_fieldSet, json, extensionRegistry); } @@ -327,7 +348,8 @@ abstract class GeneratedMessage { void addExtension(Extension extension, Object? value) { if (!extension.isRepeated) { throw ArgumentError( - 'Cannot add to a non-repeated field (use setExtension())'); + 'Cannot add to a non-repeated field (use setExtension())', + ); } _fieldSet._ensureExtensions()._ensureRepeatedField(extension).add(value); } @@ -397,8 +419,13 @@ abstract class GeneratedMessage { /// Sets the value of a non-repeated extension field to [value]. void setExtension(Extension extension, Object value) { if (_isRepeated(extension.type)) { - throw ArgumentError(_fieldSet._setFieldFailedMessage( - extension, value, 'repeating field (use get + .add())')); + throw ArgumentError( + _fieldSet._setFieldFailedMessage( + extension, + value, + 'repeating field (use get + .add())', + ), + ); } _fieldSet._ensureExtensions()._setFieldAndInfo(extension, value); } @@ -534,11 +561,11 @@ abstract class GeneratedMessage { // Support for generating a read-only default singleton instance. static final Map> - _defaultMakers = {}; + _defaultMakers = {}; static T Function() _defaultMakerFor( - T Function()? createFn) => - _getSingletonMaker(createFn!)._frozenSingletonCreator; + T Function()? createFn, + ) => _getSingletonMaker(createFn!)._frozenSingletonCreator; /// For generated code only. /// @nodoc @@ -546,7 +573,8 @@ abstract class GeneratedMessage { _getSingletonMaker(createFn)._frozenSingleton; static _SingletonMaker _getSingletonMaker( - T Function() fun) { + T Function() fun, + ) { final oldMaker = _defaultMakers[fun]; if (oldMaker != null) { // The CFE will insert an implicit downcast to `_SingletonMaker`. We @@ -589,8 +617,10 @@ extension GeneratedMessageGenericExtensions on T { /// /// Makes a writable shallow copy of this message, applies the [updates] to /// it, and marks the copy read-only before returning it. - @UseResult('[GeneratedMessageGenericExtensions.rebuild] ' - 'does not update the message, returns a new message') + @UseResult( + '[GeneratedMessageGenericExtensions.rebuild] ' + 'does not update the message, returns a new message', + ) T rebuild(void Function(T) updates) { if (!isFrozen) { throw ArgumentError('Rebuilding only works on frozen messages.'); @@ -601,7 +631,9 @@ extension GeneratedMessageGenericExtensions on T { } /// Returns a writable deep copy of this message. - @UseResult('[GeneratedMessageGenericExtensions.deepCopy] ' - 'does not update the message, returns a new message') + @UseResult( + '[GeneratedMessageGenericExtensions.deepCopy] ' + 'does not update the message, returns a new message', + ) T deepCopy() => info_.createEmptyInstance!() as T..mergeFromMessage(this); } diff --git a/protobuf/lib/src/protobuf/generated_service.dart b/protobuf/lib/src/protobuf/generated_service.dart index d3b3b0134..f2b8857ed 100644 --- a/protobuf/lib/src/protobuf/generated_service.dart +++ b/protobuf/lib/src/protobuf/generated_service.dart @@ -19,5 +19,8 @@ abstract class GeneratedService { /// Dispatches the call. The request object should come from [createRequest]. Future handleCall( - ServerContext ctx, String methodName, GeneratedMessage request); + ServerContext ctx, + String methodName, + GeneratedMessage request, + ); } diff --git a/protobuf/lib/src/protobuf/json.dart b/protobuf/lib/src/protobuf/json.dart index 1184fa633..75d4fa86c 100644 --- a/protobuf/lib/src/protobuf/json.dart +++ b/protobuf/lib/src/protobuf/json.dart @@ -58,12 +58,14 @@ Map _writeToJsonMap(_FieldSet fs) { } } - List writeMap(PbMap fieldValue, MapFieldInfo fi) => - List.from(fieldValue.entries.map((MapEntry e) => { - '${PbMap._keyFieldNumber}': convertToMap(e.key, fi.keyFieldType), - '${PbMap._valueFieldNumber}': - convertToMap(e.value, fi.valueFieldType) - })); + List writeMap(PbMap fieldValue, MapFieldInfo fi) => List.from( + fieldValue.entries.map( + (MapEntry e) => { + '${PbMap._keyFieldNumber}': convertToMap(e.key, fi.keyFieldType), + '${PbMap._valueFieldNumber}': convertToMap(e.value, fi.valueFieldType), + }, + ), + ); final result = {}; for (final fi in fs._infosSortedByTag) { @@ -72,8 +74,10 @@ Map _writeToJsonMap(_FieldSet fs) { continue; // It's missing, repeated, or an empty byte array. } if (_isMapField(fi.type)) { - result['${fi.tagNumber}'] = - writeMap(value, fi as MapFieldInfo); + result['${fi.tagNumber}'] = writeMap( + value, + fi as MapFieldInfo, + ); continue; } result['${fi.tagNumber}'] = convertToMap(value, fi.type); @@ -101,7 +105,10 @@ Map _writeToJsonMap(_FieldSet fs) { // Merge fields from a previously decoded JSON object. // (Called recursively on nested messages.) void _mergeFromJsonMap( - _FieldSet fs, Map json, ExtensionRegistry? registry) { + _FieldSet fs, + Map json, + ExtensionRegistry? registry, +) { fs._ensureWritable(); final keys = json.keys; final meta = fs._meta; @@ -116,7 +123,12 @@ void _mergeFromJsonMap( } if (fi.isMapField) { _appendJsonMap( - meta, fs, json[key], fi as MapFieldInfo, registry); + meta, + fs, + json[key], + fi as MapFieldInfo, + registry, + ); } else if (fi.isRepeated) { _appendJsonList(meta, fs, json[key], fi, registry); } else { @@ -125,8 +137,13 @@ void _mergeFromJsonMap( } } -void _appendJsonList(BuilderInfo meta, _FieldSet fs, List jsonList, - FieldInfo fi, ExtensionRegistry? registry) { +void _appendJsonList( + BuilderInfo meta, + _FieldSet fs, + List jsonList, + FieldInfo fi, + ExtensionRegistry? registry, +) { final repeated = fi._ensureRepeatedField(meta, fs); // Micro optimization. Using "for in" generates the following and iterator // alloc: @@ -134,8 +151,14 @@ void _appendJsonList(BuilderInfo meta, _FieldSet fs, List jsonList, // t4 = J.getInterceptor$ax(repeated); t1.moveNext$0();) for (var i = 0, len = jsonList.length; i < len; i++) { final value = jsonList[i]; - var convertedValue = - _convertJsonValue(meta, fs, value, fi.tagNumber, fi.type, registry); + var convertedValue = _convertJsonValue( + meta, + fs, + value, + fi.tagNumber, + fi.type, + registry, + ); // In the case of an unknown enum value, the converted value may return // null. The default enum value should be used in these cases, which is // stored in the FieldInfo. @@ -144,27 +167,34 @@ void _appendJsonList(BuilderInfo meta, _FieldSet fs, List jsonList, } } -void _appendJsonMap(BuilderInfo meta, _FieldSet fs, List jsonList, - MapFieldInfo fi, ExtensionRegistry? registry) { +void _appendJsonMap( + BuilderInfo meta, + _FieldSet fs, + List jsonList, + MapFieldInfo fi, + ExtensionRegistry? registry, +) { final entryMeta = fi.mapEntryBuilderInfo; final map = fi._ensureMapField(meta, fs); for (final jsonEntryDynamic in jsonList) { final jsonEntry = jsonEntryDynamic as Map; final entryFieldSet = _FieldSet(null, entryMeta); final convertedKey = _convertJsonValue( - entryMeta, - entryFieldSet, - jsonEntry['${PbMap._keyFieldNumber}'], - PbMap._keyFieldNumber, - fi.keyFieldType, - registry); + entryMeta, + entryFieldSet, + jsonEntry['${PbMap._keyFieldNumber}'], + PbMap._keyFieldNumber, + fi.keyFieldType, + registry, + ); var convertedValue = _convertJsonValue( - entryMeta, - entryFieldSet, - jsonEntry['${PbMap._valueFieldNumber}'], - PbMap._valueFieldNumber, - fi.valueFieldType, - registry); + entryMeta, + entryFieldSet, + jsonEntry['${PbMap._valueFieldNumber}'], + PbMap._valueFieldNumber, + fi.valueFieldType, + registry, + ); // In the case of an unknown enum value, the converted value may return // null. The default enum value should be used in these cases, which is // stored in the FieldInfo. @@ -173,10 +203,21 @@ void _appendJsonMap(BuilderInfo meta, _FieldSet fs, List jsonList, } } -void _setJsonField(BuilderInfo meta, _FieldSet fs, json, FieldInfo fi, - ExtensionRegistry? registry) { - final value = - _convertJsonValue(meta, fs, json, fi.tagNumber, fi.type, registry); +void _setJsonField( + BuilderInfo meta, + _FieldSet fs, + json, + FieldInfo fi, + ExtensionRegistry? registry, +) { + final value = _convertJsonValue( + meta, + fs, + json, + fi.tagNumber, + fi.type, + registry, + ); if (value == null) return; // _convertJsonValue throws exception when it fails to do conversion. // Therefore we run _validateField for debug builds only to validate @@ -196,8 +237,14 @@ void _setJsonField(BuilderInfo meta, _FieldSet fs, json, FieldInfo fi, /// instead. /// /// Throws [ArgumentError] if it cannot convert the value. -dynamic _convertJsonValue(BuilderInfo meta, _FieldSet fs, value, int tagNumber, - int fieldType, ExtensionRegistry? registry) { +dynamic _convertJsonValue( + BuilderInfo meta, + _FieldSet fs, + value, + int tagNumber, + int fieldType, + ExtensionRegistry? registry, +) { String expectedType; // for exception message switch (PbFieldType._baseType(fieldType)) { case PbFieldType._BOOL_BIT: diff --git a/protobuf/lib/src/protobuf/json_parsing_context.dart b/protobuf/lib/src/protobuf/json_parsing_context.dart index 3d3edddcf..99bdfdfd2 100644 --- a/protobuf/lib/src/protobuf/json_parsing_context.dart +++ b/protobuf/lib/src/protobuf/json_parsing_context.dart @@ -9,8 +9,11 @@ class JsonParsingContext { final bool supportNamesWithUnderscores; final bool permissiveEnums; - JsonParsingContext(this.ignoreUnknownFields, this.supportNamesWithUnderscores, - this.permissiveEnums); + JsonParsingContext( + this.ignoreUnknownFields, + this.supportNamesWithUnderscores, + this.permissiveEnums, + ); void addMapIndex(String index) { _path.add(index); @@ -28,7 +31,8 @@ class JsonParsingContext { Exception parseException(String message, Object? source) { final formattedPath = _path.map((s) => '["$s"]').join(); return FormatException( - 'Protobuf JSON decoding failed at: root$formattedPath. $message', - source); + 'Protobuf JSON decoding failed at: root$formattedPath. $message', + source, + ); } } diff --git a/protobuf/lib/src/protobuf/message_set.dart b/protobuf/lib/src/protobuf/message_set.dart index ba9664d64..9a0213172 100644 --- a/protobuf/lib/src/protobuf/message_set.dart +++ b/protobuf/lib/src/protobuf/message_set.dart @@ -48,8 +48,10 @@ abstract class $_MessageSet extends GeneratedMessage { } @override - void mergeFromCodedBufferReader(CodedBufferReader input, - [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { + void mergeFromCodedBufferReader( + CodedBufferReader input, [ + ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, + ]) { // Parse items. The field for the items looks like: // // repeated group Item items = 1; @@ -115,32 +117,43 @@ abstract class $_MessageSet extends GeneratedMessage { } @override - void mergeFromBuffer(List input, - [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { + void mergeFromBuffer( + List input, [ + ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, + ]) { mergeFromCodedBufferReader(CodedBufferReader(input), extensionRegistry); } void _parseExtension( - int typeId, Uint8List message, ExtensionRegistry extensionRegistry) { - final ext = - extensionRegistry.getExtension(info_.qualifiedMessageName, typeId); + int typeId, + Uint8List message, + ExtensionRegistry extensionRegistry, + ) { + final ext = extensionRegistry.getExtension( + info_.qualifiedMessageName, + typeId, + ); if (ext == null) { final messageItem = UnknownFieldSet(); - messageItem.addField(_messageSetItemTypeIdTag, - UnknownFieldSetField()..varints.add(Int64(typeId))); messageItem.addField( - _messageSetItemMessageTag, - UnknownFieldSetField() - ..lengthDelimited.add(Uint8List.fromList(message))); + _messageSetItemTypeIdTag, + UnknownFieldSetField()..varints.add(Int64(typeId)), + ); + messageItem.addField( + _messageSetItemMessageTag, + UnknownFieldSetField() + ..lengthDelimited.add(Uint8List.fromList(message)), + ); final itemListField = _fieldSet._ensureUnknownFields().getField(_messageSetItemsTag) ?? - UnknownFieldSetField(); + UnknownFieldSetField(); itemListField.addGroup(messageItem); - _fieldSet - ._ensureUnknownFields() - .addField(_messageSetItemsTag, itemListField); + _fieldSet._ensureUnknownFields().addField( + _messageSetItemsTag, + itemListField, + ); } else { setExtension(ext, ext.subBuilder!()..mergeFromBuffer(message)); } diff --git a/protobuf/lib/src/protobuf/mixins/map_mixin.dart b/protobuf/lib/src/protobuf/mixins/map_mixin.dart index a8d9c2ee0..71b389820 100644 --- a/protobuf/lib/src/protobuf/mixins/map_mixin.dart +++ b/protobuf/lib/src/protobuf/mixins/map_mixin.dart @@ -29,8 +29,11 @@ mixin PbMapMixin { void operator []=(Object? key, Object? val) { final tag = getTagNumber(key as String); if (tag == null) { - throw ArgumentError.value(key, 'key', - "field '$key' not found in ${info_.qualifiedMessageName}"); + throw ArgumentError.value( + key, + 'key', + "field '$key' not found in ${info_.qualifiedMessageName}", + ); } setField(tag, val!); } @@ -43,6 +46,7 @@ mixin PbMapMixin { dynamic remove(Object? key) { throw UnsupportedError( - 'remove() not supported by ${info_.qualifiedMessageName}'); + 'remove() not supported by ${info_.qualifiedMessageName}', + ); } } diff --git a/protobuf/lib/src/protobuf/mixins/well_known.dart b/protobuf/lib/src/protobuf/mixins/well_known.dart index 2c79c49eb..644d92a0f 100644 --- a/protobuf/lib/src/protobuf/mixins/well_known.dart +++ b/protobuf/lib/src/protobuf/mixins/well_known.dart @@ -32,10 +32,16 @@ mixin AnyMixin implements GeneratedMessage { /// A typical usage would be `any.unpackInto(Message())`. /// /// Returns [instance]. - T unpackInto(T instance, - {ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY}) { - unpackIntoHelper(value, instance, typeUrl, - extensionRegistry: extensionRegistry); + T unpackInto( + T instance, { + ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, + }) { + unpackIntoHelper( + value, + instance, + typeUrl, + extensionRegistry: extensionRegistry, + ); return instance; } @@ -43,8 +49,11 @@ mixin AnyMixin implements GeneratedMessage { /// /// The [typeUrl] will be [typeUrlPrefix]/`fullName` where `fullName` is /// the fully qualified name of the type of [message]. - static void packIntoAny(AnyMixin target, GeneratedMessage message, - {String typeUrlPrefix = 'type.googleapis.com'}) { + static void packIntoAny( + AnyMixin target, + GeneratedMessage message, { + String typeUrlPrefix = 'type.googleapis.com', + }) { target.value = message.writeToBuffer(); target.typeUrl = '$typeUrlPrefix/${message.info_.qualifiedMessageName}'; } @@ -78,12 +87,15 @@ mixin AnyMixin implements GeneratedMessage { // "value": "1.212s" // } static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { final any = message as AnyMixin; final info = typeRegistry.lookup(_typeNameFromUrl(any.typeUrl)); if (info == null) { throw ArgumentError( - 'The type of the Any message (${any.typeUrl}) is not in the given typeRegistry.'); + 'The type of the Any message (${any.typeUrl}) is not in the given typeRegistry.', + ); } final unpacked = info.createEmptyInstance!()..mergeFromBuffer(any.value); final proto3Json = unpacked.toProto3Json(typeRegistry: typeRegistry); @@ -96,11 +108,17 @@ mixin AnyMixin implements GeneratedMessage { } } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is! Map) { throw context.parseException( - 'Expected Any message encoded as {@type,...},', json); + 'Expected Any message encoded as {@type,...},', + json, + ); } final object = json; final typeUrl = object['@type']; @@ -110,21 +128,25 @@ mixin AnyMixin implements GeneratedMessage { final info = typeRegistry.lookup(_typeNameFromUrl(typeUrl)); if (info == null) { throw context.parseException( - 'Decoding Any of type $typeUrl not in TypeRegistry $typeRegistry', - json); + 'Decoding Any of type $typeUrl not in TypeRegistry $typeRegistry', + json, + ); } - final Object? subJson = info.fromProto3Json == null - // TODO(sigurdm): avoid cloning [object] here. - ? (Map.from(object)..remove('@type')) - : object['value']; + final Object? subJson = + info.fromProto3Json == null + // TODO(sigurdm): avoid cloning [object] here. + ? (Map.from(object)..remove('@type')) + : object['value']; // TODO(sigurdm): We lose [context.path]. - final packedMessage = info.createEmptyInstance!() - ..mergeFromProto3Json(subJson, + final packedMessage = + info.createEmptyInstance!()..mergeFromProto3Json( + subJson, typeRegistry: typeRegistry, supportNamesWithUnderscores: context.supportNamesWithUnderscores, ignoreUnknownFields: context.ignoreUnknownFields, - permissiveEnums: context.permissiveEnums); + permissiveEnums: context.permissiveEnums, + ); any.value = packedMessage.writeToBuffer(); any.typeUrl = typeUrl; @@ -156,8 +178,9 @@ mixin TimestampMixin { /// Use [toLocal] to convert to local time zone, instead of the default UTC. DateTime toDateTime({bool toLocal = false}) => DateTime.fromMicrosecondsSinceEpoch( - seconds.toInt() * Duration.microsecondsPerSecond + nanos ~/ 1000, - isUtc: !toLocal); + seconds.toInt() * Duration.microsecondsPerSecond + nanos ~/ 1000, + isUtc: !toLocal, + ); /// Updates [target] to be the time at [dateTime]. /// @@ -193,21 +216,27 @@ mixin TimestampMixin { // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { final timestamp = message as TimestampMixin; final dateTime = timestamp.toDateTime(); if (timestamp.nanos < 0) { throw ArgumentError( - 'Timestamp with negative `nanos`: ${timestamp.nanos}'); + 'Timestamp with negative `nanos`: ${timestamp.nanos}', + ); } if (timestamp.nanos > 999999999) { throw ArgumentError( - 'Timestamp with `nanos` out of range: ${timestamp.nanos}'); + 'Timestamp with `nanos` out of range: ${timestamp.nanos}', + ); } if (dateTime.isBefore(_minTimestamp) || dateTime.isAfter(_maxTimestamp)) { - throw ArgumentError('Timestamp Must be from 0001-01-01T00:00:00Z to ' - '9999-12-31T23:59:59Z inclusive. Was: ${dateTime.toIso8601String()}'); + throw ArgumentError( + 'Timestamp Must be from 0001-01-01T00:00:00Z to ' + '9999-12-31T23:59:59Z inclusive. Was: ${dateTime.toIso8601String()}', + ); } // Because [DateTime] doesn't have nano-second precision, we cannot use @@ -226,8 +255,12 @@ mixin TimestampMixin { return '$y-$m-${d}T$h:$min:$sec${secFrac}Z'; } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is String) { var jsonWithoutFracSec = json; var nanos = 0; @@ -236,23 +269,32 @@ mixin TimestampMixin { final fracSecs = fracSecsMatch[1]!; if (fracSecs.length > 9) { throw context.parseException( - 'Timestamp can have at most than 9 decimal digits', json); + 'Timestamp can have at most than 9 decimal digits', + json, + ); } nanos = int.parse(fracSecs.padRight(9, '0')); - jsonWithoutFracSec = - json.replaceRange(fracSecsMatch.start, fracSecsMatch.end, ''); + jsonWithoutFracSec = json.replaceRange( + fracSecsMatch.start, + fracSecsMatch.end, + '', + ); } final dateTimeWithoutFractionalSeconds = DateTime.tryParse(jsonWithoutFracSec) ?? - (throw context.parseException( - 'Timestamp not well formatted. ', json)); + (throw context.parseException( + 'Timestamp not well formatted. ', + json, + )); final timestamp = message as TimestampMixin; setFromDateTime(timestamp, dateTimeWithoutFractionalSeconds); timestamp.nanos = nanos; } else { throw context.parseException( - 'Expected timestamp represented as String', json); + 'Expected timestamp represented as String', + json, + ); } } } @@ -267,7 +309,9 @@ mixin DurationMixin { static final RegExp finalZeroes = RegExp(r'0+$'); static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { final duration = message as DurationMixin; final secFrac = duration.nanos // nanos and seconds should always have the same sign. @@ -281,14 +325,20 @@ mixin DurationMixin { static final RegExp durationPattern = RegExp(r'(-?\d*)(?:\.(\d*))?s$'); - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { final duration = message as DurationMixin; if (json is String) { final match = durationPattern.matchAsPrefix(json); if (match == null) { throw context.parseException( - 'Expected a String of the form `.s`', json); + 'Expected a String of the form `.s`', + json, + ); } else { final secondsString = match[1]!; final seconds = @@ -299,7 +349,9 @@ mixin DurationMixin { } } else { throw context.parseException( - 'Expected a String of the form `.s`', json); + 'Expected a String of the form `.s`', + json, + ); } } } @@ -311,14 +363,22 @@ mixin StructMixin implements GeneratedMessage { // From google/protobuf/struct.proto: // The JSON representation for `Struct` is JSON object. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { final struct = message as StructMixin; - return struct.fields.map((key, value) => - MapEntry(key, ValueMixin.toProto3JsonHelper(value, typeRegistry))); - } - - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + return struct.fields.map( + (key, value) => + MapEntry(key, ValueMixin.toProto3JsonHelper(value, typeRegistry)), + ); + } + + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is Map) { // Check for emptiness to avoid setting `.fields` if there are no // values. @@ -341,7 +401,9 @@ mixin StructMixin implements GeneratedMessage { } } else { throw context.parseException( - 'Expected a JSON object literal (map)', json); + 'Expected a JSON object literal (map)', + json, + ); } } } @@ -374,7 +436,9 @@ mixin ValueMixin implements GeneratedMessage { // From google/protobuf/struct.proto: // The JSON representation for `Value` is JSON value static Object? toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { final value = message as ValueMixin; // This would ideally be a switch, but we cannot import the enum we are // switching over. @@ -395,8 +459,12 @@ mixin ValueMixin implements GeneratedMessage { } } - static void fromProto3JsonHelper(GeneratedMessage message, Object? json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object? json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { final value = message as ValueMixin; if (json == null) { // Rely on the getter retrieving the default to provide an instance. @@ -411,18 +479,27 @@ mixin ValueMixin implements GeneratedMessage { // Clone because the default instance is frozen. final structValue = value.structValue.deepCopy(); StructMixin.fromProto3JsonHelper( - structValue, json, typeRegistry, context); + structValue, + json, + typeRegistry, + context, + ); value.structValue = structValue; } else if (json is List) { // Clone because the default instance is frozen. final listValue = value.listValue.deepCopy(); ListValueMixin.fromProto3JsonHelper( - listValue, json, typeRegistry, context); + listValue, + json, + typeRegistry, + context, + ); value.listValue = listValue; } else { throw context.parseException( - 'Expected a json-value (Map, List, String, number, bool or null)', - json); + 'Expected a json-value (Map, List, String, number, bool or null)', + json, + ); } } } @@ -433,7 +510,9 @@ mixin ListValueMixin implements GeneratedMessage { // From google/protobuf/struct.proto: // The JSON representation for `ListValue` is JSON array. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { final list = message as ListValueMixin; return list.values .map((value) => ValueMixin.toProto3JsonHelper(value, typeRegistry)) @@ -442,8 +521,12 @@ mixin ListValueMixin implements GeneratedMessage { static const _valueFieldTagNumber = 1; - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { final list = message as ListValueMixin; if (json is List) { final subBuilder = message.info_.subBuilder(_valueFieldTagNumber)!; @@ -471,45 +554,60 @@ mixin FieldMaskMixin { // separated by a comma. Fields name in each path are converted // to/from lower-camel naming conventions. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { final fieldMask = message as FieldMaskMixin; for (final path in fieldMask.paths) { if (path.contains(RegExp('[A-Z]|_[^a-z]'))) { throw ArgumentError( - 'Bad fieldmask $path. Does not round-trip to json.'); + 'Bad fieldmask $path. Does not round-trip to json.', + ); } } return fieldMask.paths.map(_toCamelCase).join(','); } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is String) { if (json.contains('_')) { throw context.parseException( - 'Invalid Character `_` in FieldMask', json); + 'Invalid Character `_` in FieldMask', + json, + ); } if (json == '') { // The empty string splits to a single value. So this is a special case. return; } - (message as FieldMaskMixin) - .paths - .addAll(json.split(',').map(_fromCamelCase)); + (message as FieldMaskMixin).paths.addAll( + json.split(',').map(_fromCamelCase), + ); } else { throw context.parseException( - 'Expected String formatted as FieldMask', json); + 'Expected String formatted as FieldMask', + json, + ); } } static String _toCamelCase(String name) { return name.replaceAllMapped( - RegExp('_([a-z])'), (Match m) => m.group(1)!.toUpperCase()); + RegExp('_([a-z])'), + (Match m) => m.group(1)!.toUpperCase(), + ); } static String _fromCamelCase(String name) { return name.replaceAllMapped( - RegExp('[A-Z]'), (Match m) => '_${m.group(0)!.toLowerCase()}'); + RegExp('[A-Z]'), + (Match m) => '_${m.group(0)!.toLowerCase()}', + ); } } @@ -520,21 +618,32 @@ mixin DoubleValueMixin { // From google/protobuf/wrappers.proto: // The JSON representation for `DoubleValue` is JSON number. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return (message as DoubleValueMixin).value; } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is num) { (message as DoubleValueMixin).value = json.toDouble(); } else if (json is String) { - (message as DoubleValueMixin).value = double.tryParse(json) ?? + (message as DoubleValueMixin).value = + double.tryParse(json) ?? (throw context.parseException( - 'Expected string to encode a double', json)); + 'Expected string to encode a double', + json, + )); } else { throw context.parseException( - 'Expected a double as a String or number', json); + 'Expected a double as a String or number', + json, + ); } } } @@ -546,21 +655,32 @@ mixin FloatValueMixin { // From google/protobuf/wrappers.proto: // The JSON representation for `FloatValue` is JSON number. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return (message as FloatValueMixin).value; } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is num) { (message as FloatValueMixin).value = json.toDouble(); } else if (json is String) { - (message as FloatValueMixin).value = double.tryParse(json) ?? + (message as FloatValueMixin).value = + double.tryParse(json) ?? (throw context.parseException( - 'Expected a float as a String or number', json)); + 'Expected a float as a String or number', + json, + )); } else { throw context.parseException( - 'Expected a float as a String or number', json); + 'Expected a float as a String or number', + json, + ); } } } @@ -572,12 +692,18 @@ mixin Int64ValueMixin { // From google/protobuf/wrappers.proto: // The JSON representation for `Int64Value` is JSON string. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return (message as Int64ValueMixin).value.toString(); } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is int) { (message as Int64ValueMixin).value = Int64(json); } else if (json is String) { @@ -588,7 +714,9 @@ mixin Int64ValueMixin { } } else { throw context.parseException( - 'Expected an integer encoded as a String or number', json); + 'Expected an integer encoded as a String or number', + json, + ); } } } @@ -600,12 +728,18 @@ mixin UInt64ValueMixin { // From google/protobuf/wrappers.proto: // The JSON representation for `UInt64Value` is JSON string. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return (message as UInt64ValueMixin).value.toStringUnsigned(); } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is int) { (message as UInt64ValueMixin).value = Int64(json); } else if (json is String) { @@ -613,11 +747,15 @@ mixin UInt64ValueMixin { (message as UInt64ValueMixin).value = Int64.parseInt(json); } on FormatException { throw context.parseException( - 'Expected string to encode unsigned integer', json); + 'Expected string to encode unsigned integer', + json, + ); } } else { throw context.parseException( - 'Expected an unsigned integer as a String or integer', json); + 'Expected an unsigned integer as a String or integer', + json, + ); } } } @@ -629,21 +767,32 @@ mixin Int32ValueMixin { // From google/protobuf/wrappers.proto: // The JSON representation for `Int32Value` is JSON number. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return (message as Int32ValueMixin).value; } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is int) { (message as Int32ValueMixin).value = json; } else if (json is String) { - (message as Int32ValueMixin).value = int.tryParse(json) ?? + (message as Int32ValueMixin).value = + int.tryParse(json) ?? (throw context.parseException( - 'Expected string to encode integer', json)); + 'Expected string to encode integer', + json, + )); } else { throw context.parseException( - 'Expected an integer encoded as a String or number', json); + 'Expected an integer encoded as a String or number', + json, + ); } } } @@ -653,23 +802,34 @@ mixin UInt32ValueMixin { set value(int value); static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return (message as UInt32ValueMixin).value; } // From google/protobuf/wrappers.proto: // The JSON representation for `UInt32Value` is JSON number. - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is int) { (message as UInt32ValueMixin).value = json; } else if (json is String) { - (message as UInt32ValueMixin).value = int.tryParse(json) ?? + (message as UInt32ValueMixin).value = + int.tryParse(json) ?? (throw context.parseException( - 'Expected String to encode an integer', json)); + 'Expected String to encode an integer', + json, + )); } else { throw context.parseException( - 'Expected an unsigned integer as a String or integer', json); + 'Expected an unsigned integer as a String or integer', + json, + ); } } } @@ -681,12 +841,18 @@ mixin BoolValueMixin { // From google/protobuf/wrappers.proto: // The JSON representation for `BoolValue` is JSON `true` and `false` static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return (message as BoolValueMixin).value; } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is bool) { (message as BoolValueMixin).value = json; } else { @@ -702,12 +868,18 @@ mixin StringValueMixin { // From google/protobuf/wrappers.proto: // The JSON representation for `StringValue` is JSON string. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return (message as StringValueMixin).value; } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is String) { (message as StringValueMixin).value = json; } else { @@ -723,22 +895,32 @@ mixin BytesValueMixin { // From google/protobuf/wrappers.proto: // The JSON representation for `BytesValue` is JSON string. static Object toProto3JsonHelper( - GeneratedMessage message, TypeRegistry typeRegistry) { + GeneratedMessage message, + TypeRegistry typeRegistry, + ) { return base64.encode((message as BytesValueMixin).value); } - static void fromProto3JsonHelper(GeneratedMessage message, Object json, - TypeRegistry typeRegistry, JsonParsingContext context) { + static void fromProto3JsonHelper( + GeneratedMessage message, + Object json, + TypeRegistry typeRegistry, + JsonParsingContext context, + ) { if (json is String) { try { (message as BytesValueMixin).value = base64.decode(json); } on FormatException { throw context.parseException( - 'Expected bytes encoded as base64 String', json); + 'Expected bytes encoded as base64 String', + json, + ); } } else { throw context.parseException( - 'Expected bytes encoded as base64 String', json); + 'Expected bytes encoded as base64 String', + json, + ); } } } diff --git a/protobuf/lib/src/protobuf/pb_list.dart b/protobuf/lib/src/protobuf/pb_list.dart index 0e0ccc1de..9d880f557 100644 --- a/protobuf/lib/src/protobuf/pb_list.dart +++ b/protobuf/lib/src/protobuf/pb_list.dart @@ -32,17 +32,17 @@ class PbList extends ListBase { bool get isFrozen => _isReadOnly; PbList({CheckFunc check = _checkNotNull}) - : _wrappedList = [], - _check = check; + : _wrappedList = [], + _check = check; PbList.unmodifiable() - : _wrappedList = _emptyList, - _check = _checkNotNull, - _isReadOnly = true; + : _wrappedList = _emptyList, + _check = _checkNotNull, + _isReadOnly = true; PbList.from(List from) - : _wrappedList = List.from(from), - _check = _checkNotNull; + : _wrappedList = List.from(from), + _check = _checkNotNull; @override @pragma('dart2js:never-inline') diff --git a/protobuf/lib/src/protobuf/pb_map.dart b/protobuf/lib/src/protobuf/pb_map.dart index 420e6750f..44337fb26 100644 --- a/protobuf/lib/src/protobuf/pb_map.dart +++ b/protobuf/lib/src/protobuf/pb_map.dart @@ -34,8 +34,8 @@ class PbMap extends MapBase { PbMap(this.keyFieldType, this.valueFieldType) : _wrappedMap = {}; PbMap.unmodifiable(this.keyFieldType, this.valueFieldType) - : _wrappedMap = {}, - _isReadOnly = true; + : _wrappedMap = {}, + _isReadOnly = true; @override V? operator [](Object? key) => _wrappedMap[key]; @@ -75,8 +75,10 @@ class PbMap extends MapBase { /// pairs in any order. Then, the `hashCode` is guaranteed to be the same. @override int get hashCode { - return _wrappedMap.entries - .fold(0, (h, entry) => h ^ _HashUtils._hash2(entry.key, entry.value)); + return _wrappedMap.entries.fold( + 0, + (h, entry) => h ^ _HashUtils._hash2(entry.key, entry.value), + ); } @override @@ -98,8 +100,11 @@ class PbMap extends MapBase { return _wrappedMap.remove(key); } - void _mergeEntry(BuilderInfo mapEntryMeta, CodedBufferReader input, - ExtensionRegistry registry) { + void _mergeEntry( + BuilderInfo mapEntryMeta, + CodedBufferReader input, + ExtensionRegistry registry, + ) { final length = input.readInt32(); final oldLimit = input._currentLimit; input._currentLimit = input._bufferPos + length; diff --git a/protobuf/lib/src/protobuf/proto3_json.dart b/protobuf/lib/src/protobuf/proto3_json.dart index c40806d4a..c2bbf29c7 100644 --- a/protobuf/lib/src/protobuf/proto3_json.dart +++ b/protobuf/lib/src/protobuf/proto3_json.dart @@ -37,7 +37,9 @@ Object? _writeToProto3Json(_FieldSet fs, TypeRegistry typeRegistry) { if (_isGroupOrMessage(fieldType!)) { return _writeToProto3Json( - (fieldValue as GeneratedMessage)._fieldSet, typeRegistry); + (fieldValue as GeneratedMessage)._fieldSet, + typeRegistry, + ); } else if (_isEnum(fieldType)) { return (fieldValue as ProtobufEnum).name; } else { @@ -77,7 +79,8 @@ Object? _writeToProto3Json(_FieldSet fs, TypeRegistry typeRegistry) { return base64Encode(fieldValue); default: throw StateError( - 'Invariant violation: unexpected value type $fieldType'); + 'Invariant violation: unexpected value type $fieldType', + ); } } } @@ -97,13 +100,16 @@ Object? _writeToProto3Json(_FieldSet fs, TypeRegistry typeRegistry) { if (fieldInfo.isMapField) { jsonValue = (value as PbMap).map((key, entryValue) { final mapEntryInfo = fieldInfo as MapFieldInfo; - return MapEntry(convertToMapKey(key, mapEntryInfo.keyFieldType), - valueToProto3Json(entryValue, mapEntryInfo.valueFieldType)); + return MapEntry( + convertToMapKey(key, mapEntryInfo.keyFieldType), + valueToProto3Json(entryValue, mapEntryInfo.valueFieldType), + ); }); } else if (fieldInfo.isRepeated) { - jsonValue = (value as PbList) - .map((element) => valueToProto3Json(element, fieldInfo.type)) - .toList(); + jsonValue = + (value as PbList) + .map((element) => valueToProto3Json(element, fieldInfo.type)) + .toList(); } else { jsonValue = valueToProto3Json(value, fieldInfo.type); } @@ -153,15 +159,19 @@ extension _FindFirst on Iterable { /// Merge a JSON object representing a message in proto3 JSON format ([json]) /// to [fieldSet]. void _mergeFromProto3Json( - Object? json, - _FieldSet fieldSet, - TypeRegistry typeRegistry, - bool ignoreUnknownFields, - bool supportNamesWithUnderscores, - bool permissiveEnums) { + Object? json, + _FieldSet fieldSet, + TypeRegistry typeRegistry, + bool ignoreUnknownFields, + bool supportNamesWithUnderscores, + bool permissiveEnums, +) { fieldSet._ensureWritable(); final context = JsonParsingContext( - ignoreUnknownFields, supportNamesWithUnderscores, permissiveEnums); + ignoreUnknownFields, + supportNamesWithUnderscores, + permissiveEnums, + ); void recursionHelper(Object? json, _FieldSet fieldSet) { Object? convertProto3JsonValue(Object value, FieldInfo fieldInfo) { @@ -179,12 +189,16 @@ void _mergeFromProto3Json( result = base64Decode(value); } on FormatException { throw context.parseException( - 'Expected bytes encoded as base64 String', json); + 'Expected bytes encoded as base64 String', + json, + ); } return result; } throw context.parseException( - 'Expected bytes encoded as base64 String', value); + 'Expected bytes encoded as base64 String', + value, + ); case PbFieldType._STRING_BIT: if (value is String) { return value; @@ -199,17 +213,23 @@ void _mergeFromProto3Json( } else if (value is String) { return double.tryParse(value) ?? (throw context.parseException( - 'Expected String to encode a double', value)); + 'Expected String to encode a double', + value, + )); } throw context.parseException( - 'Expected a double represented as a String or number', value); + 'Expected a double represented as a String or number', + value, + ); case PbFieldType._ENUM_BIT: if (value is String) { // TODO(sigurdm): Do we want to avoid linear search here? Measure... - final result = permissiveEnums - ? fieldInfo.enumValues! - .findFirst((e) => permissiveCompare(e.name, value)) - : fieldInfo.enumValues!.findFirst((e) => e.name == value); + final result = + permissiveEnums + ? fieldInfo.enumValues!.findFirst( + (e) => permissiveCompare(e.name, value), + ) + : fieldInfo.enumValues!.findFirst((e) => e.name == value); if ((result != null) || ignoreUnknownFields) return result; throw context.parseException('Unknown enum value', value); } else if (value is int) { @@ -217,10 +237,14 @@ void _mergeFromProto3Json( (ignoreUnknownFields ? null : (throw context.parseException( - 'Unknown enum value', value))); + 'Unknown enum value', + value, + ))); } throw context.parseException( - 'Expected enum as a string or integer', value); + 'Expected enum as a string or integer', + value, + ); case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: int result; @@ -230,7 +254,9 @@ void _mergeFromProto3Json( result = _tryParse32BitProto3(value, context); } else { throw context.parseException( - 'Expected int or stringified int', value); + 'Expected int or stringified int', + value, + ); } return _check32BitUnsignedProto3(result, context); case PbFieldType._INT32_BIT: @@ -243,7 +269,9 @@ void _mergeFromProto3Json( result = _tryParse32BitProto3(value, context); } else { throw context.parseException( - 'Expected int or stringified int', value); + 'Expected int or stringified int', + value, + ); } _check32BitSignedProto3(result, context); return result; @@ -255,7 +283,9 @@ void _mergeFromProto3Json( result = _tryParse64BitProto3(json, value, context); } else { throw context.parseException( - 'Expected int or stringified int', value); + 'Expected int or stringified int', + value, + ); } return result; case PbFieldType._INT64_BIT: @@ -269,12 +299,16 @@ void _mergeFromProto3Json( result = Int64.parseInt(value); } on FormatException { throw context.parseException( - 'Expected int or stringified int', value); + 'Expected int or stringified int', + value, + ); } return result; } throw context.parseException( - 'Expected int or stringified int', value); + 'Expected int or stringified int', + value, + ); case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: final subMessage = fieldInfo.subBuilder!(); @@ -295,7 +329,9 @@ void _mergeFromProto3Json( return false; default: throw context.parseException( - 'Wrong boolean key, should be one of ("true", "false")', key); + 'Wrong boolean key, should be one of ("true", "false")', + key, + ); } case PbFieldType._STRING_BIT: return key; @@ -313,10 +349,14 @@ void _mergeFromProto3Json( case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: return _check32BitSignedProto3( - _tryParse32BitProto3(key, context), context); + _tryParse32BitProto3(key, context), + context, + ); case PbFieldType._UINT32_BIT: return _check32BitUnsignedProto3( - _tryParse32BitProto3(key, context), context); + _tryParse32BitProto3(key, context), + context, + ); default: throw StateError('Not a valid key type $fieldType'); } @@ -348,8 +388,9 @@ void _mergeFromProto3Json( if (fieldInfo == null && supportNamesWithUnderscores) { // We don't optimize for field names with underscores, instead do a // linear search for the index. - fieldInfo = byName.values - .findFirst((FieldInfo info) => info.protoName == key); + fieldInfo = byName.values.findFirst( + (FieldInfo info) => info.protoName == key, + ); } if (fieldInfo == null) { if (ignoreUnknownFields) { @@ -368,9 +409,13 @@ void _mergeFromProto3Json( throw context.parseException('Expected a String key', subKey); } context.addMapIndex(subKey); - fieldValues[decodeMapKey(subKey, mapFieldInfo.keyFieldType)] = - convertProto3JsonValue( - subValue, mapFieldInfo.valueFieldInfo); + fieldValues[decodeMapKey( + subKey, + mapFieldInfo.keyFieldType, + )] = convertProto3JsonValue( + subValue, + mapFieldInfo.valueFieldInfo, + ); context.popIndex(); }); } else { @@ -397,13 +442,19 @@ void _mergeFromProto3Json( fieldSet._values[fieldInfo.index!]; if (original == null) { fieldSet._setNonExtensionFieldUnchecked( - meta, fieldInfo, parsedSubMessage); + meta, + fieldInfo, + parsedSubMessage, + ); } else { original.mergeFromMessage(parsedSubMessage); } } else { fieldSet._setFieldUnchecked( - meta, fieldInfo, convertProto3JsonValue(value, fieldInfo)); + meta, + fieldInfo, + convertProto3JsonValue(value, fieldInfo), + ); } context.popIndex(); }); diff --git a/protobuf/lib/src/protobuf/protobuf_enum.dart b/protobuf/lib/src/protobuf/protobuf_enum.dart index 46c173e33..73779fb25 100644 --- a/protobuf/lib/src/protobuf/protobuf_enum.dart +++ b/protobuf/lib/src/protobuf/protobuf_enum.dart @@ -57,7 +57,9 @@ class ProtobufEnum { /// /// @nodoc static List $_initByValueList( - List enumValues, int maxEnumValue) { + List enumValues, + int maxEnumValue, + ) { final byValue = List.filled(maxEnumValue + 1, null); for (final enumValue in enumValues) { byValue[enumValue.value] = enumValue; diff --git a/protobuf/lib/src/protobuf/rpc_client.dart b/protobuf/lib/src/protobuf/rpc_client.dart index 776eb01d1..6239674e3 100644 --- a/protobuf/lib/src/protobuf/rpc_client.dart +++ b/protobuf/lib/src/protobuf/rpc_client.dart @@ -28,9 +28,10 @@ abstract class RpcClient { /// appropriate. It should merge the reply into [emptyResponse] and /// return it. Future invoke( - ClientContext? ctx, - String serviceName, - String methodName, - GeneratedMessage request, - T emptyResponse); + ClientContext? ctx, + String serviceName, + String methodName, + GeneratedMessage request, + T emptyResponse, + ); } diff --git a/protobuf/lib/src/protobuf/type_registry.dart b/protobuf/lib/src/protobuf/type_registry.dart index 4485a7a23..d1b9c89c5 100644 --- a/protobuf/lib/src/protobuf/type_registry.dart +++ b/protobuf/lib/src/protobuf/type_registry.dart @@ -21,8 +21,12 @@ class TypeRegistry { /// TypeRegistry([Foo(), Bar()]); /// ``` TypeRegistry(Iterable types) - : _mapping = Map.fromEntries(types.map((message) => - MapEntry(message.info_.qualifiedMessageName, message.info_))); + : _mapping = Map.fromEntries( + types.map( + (message) => + MapEntry(message.info_.qualifiedMessageName, message.info_), + ), + ); const TypeRegistry.empty() : _mapping = const {}; diff --git a/protobuf/lib/src/protobuf/unknown_field_set.dart b/protobuf/lib/src/protobuf/unknown_field_set.dart index aa4fe6c35..b0579a913 100644 --- a/protobuf/lib/src/protobuf/unknown_field_set.dart +++ b/protobuf/lib/src/protobuf/unknown_field_set.dart @@ -6,8 +6,8 @@ part of '../../protobuf.dart'; /// A set of unknown fields in a [GeneratedMessage]. class UnknownFieldSet { - static final UnknownFieldSet emptyUnknownFieldSet = UnknownFieldSet() - .._markReadOnly(); + static final UnknownFieldSet emptyUnknownFieldSet = + UnknownFieldSet().._markReadOnly(); final Map _fields = {}; UnknownFieldSet(); @@ -271,12 +271,12 @@ class UnknownFieldSetField { } List get values => [ - ...lengthDelimited, - ...varints, - ...fixed32s, - ...fixed64s, - ...groups, - ]; + ...lengthDelimited, + ...varints, + ...fixed32s, + ...fixed64s, + ...groups, + ]; void writeTo(int fieldNumber, CodedBufferWriter output) { void write(int type, value) { diff --git a/protobuf/lib/src/protobuf/unpack.dart b/protobuf/lib/src/protobuf/unpack.dart index 14a27260e..aed3260bf 100644 --- a/protobuf/lib/src/protobuf/unpack.dart +++ b/protobuf/lib/src/protobuf/unpack.dart @@ -13,8 +13,11 @@ part of '../../protobuf.dart'; /// /// @nodoc void unpackIntoHelper( - List value, T instance, String typeUrl, - {ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY}) { + List value, + T instance, + String typeUrl, { + ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, +}) { // From "google/protobuf/any.proto": // // The pack methods provided by protobuf library will by default use @@ -25,7 +28,9 @@ void unpackIntoHelper( if (!canUnpackIntoHelper(instance, typeUrl)) { final typeName = instance.info_.qualifiedMessageName; throw InvalidProtocolBufferException.wrongAnyMessage( - _typeNameFromUrl(typeUrl), typeName); + _typeNameFromUrl(typeUrl), + typeName, + ); } instance.mergeFromBuffer(value, extensionRegistry); } diff --git a/protobuf/pubspec.yaml b/protobuf/pubspec.yaml index d8e418363..9bdd790a5 100644 --- a/protobuf/pubspec.yaml +++ b/protobuf/pubspec.yaml @@ -1,12 +1,12 @@ name: protobuf -version: 4.1.0 +version: 4.1.1-wip description: >- Runtime library for protocol buffers support. Use with package:protoc_plugin to generate Dart code for your '.proto' files. repository: https://github.com/google/protobuf.dart/tree/master/protobuf environment: - sdk: ^3.6.0 + sdk: ^3.7.0 resolution: workspace diff --git a/protobuf/test/codec_test.dart b/protobuf/test/codec_test.dart index ac7b28340..215e90d7f 100644 --- a/protobuf/test/codec_test.dart +++ b/protobuf/test/codec_test.dart @@ -15,13 +15,14 @@ void main() { ByteData makeData(Uint8List bytes) => ByteData.view(bytes.buffer); Uint8List Function(dynamic) convertToBytes(fieldType) => (value) { - final writer = CodedBufferWriter()..writeField(0, fieldType, value); - return writer.toBuffer().sublist(1); - }; - - RoundtripTester roundtripTester( - {T Function(CodedBufferReader bytes)? fromBytes, - List Function(T value)? toBytes}) { + final writer = CodedBufferWriter()..writeField(0, fieldType, value); + return writer.toBuffer().sublist(1); + }; + + RoundtripTester roundtripTester({ + T Function(CodedBufferReader bytes)? fromBytes, + List Function(T value)? toBytes, + }) { return (T value, List bytes) { expect(fromBytes!(CodedBufferReader(bytes)), equals(value)); expect(toBytes!(value), bytes); @@ -32,23 +33,35 @@ void main() { test('testInt32RoundTrips', () { final roundtrip = roundtripTester( - fromBytes: (CodedBufferReader reader) => reader.readInt32(), - toBytes: int32ToBytes); + fromBytes: (CodedBufferReader reader) => reader.readInt32(), + toBytes: int32ToBytes, + ); roundtrip(0, [0x00]); roundtrip(1, [0x01]); roundtrip(206, [0xce, 0x01]); roundtrip(300, [0xac, 0x02]); roundtrip(2147483647, [0xff, 0xff, 0xff, 0xff, 0x07]); - roundtrip(-2147483648, - [0x80, 0x80, 0x80, 0x80, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x01]); + roundtrip(-2147483648, [ + 0x80, + 0x80, + 0x80, + 0x80, + 0xf8, + 0xff, + 0xff, + 0xff, + 0xff, + 0x01, + ]); roundtrip(-1, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]); roundtrip(-2, [0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]); }); test('testSint32', () { final roundtrip = roundtripTester( - fromBytes: (CodedBufferReader reader) => reader.readSint32(), - toBytes: convertToBytes(PbFieldType.OS3)); + fromBytes: (CodedBufferReader reader) => reader.readSint32(), + toBytes: convertToBytes(PbFieldType.OS3), + ); roundtrip(0, [0x00]); roundtrip(-1, [0x01]); @@ -58,8 +71,9 @@ void main() { test('testSint64', () { final roundtrip = roundtripTester( - fromBytes: (CodedBufferReader reader) => reader.readSint64(), - toBytes: convertToBytes(PbFieldType.OS6)); + fromBytes: (CodedBufferReader reader) => reader.readSint64(), + toBytes: convertToBytes(PbFieldType.OS6), + ); roundtrip(make64(0), [0x00]); roundtrip(make64(-1), [0x01]); @@ -69,8 +83,9 @@ void main() { test('testFixed32', () { final roundtrip = roundtripTester( - fromBytes: (CodedBufferReader reader) => reader.readFixed32(), - toBytes: convertToBytes(PbFieldType.OF3)); + fromBytes: (CodedBufferReader reader) => reader.readFixed32(), + toBytes: convertToBytes(PbFieldType.OF3), + ); roundtrip(0, [0x00, 0x00, 0x00, 0x00]); roundtrip(1, [0x01, 0x00, 0x00, 0x00]); @@ -80,21 +95,39 @@ void main() { test('testFixed64', () { final roundtrip = roundtripTester( - fromBytes: (CodedBufferReader reader) => reader.readFixed64(), - toBytes: convertToBytes(PbFieldType.OF6)); + fromBytes: (CodedBufferReader reader) => reader.readFixed64(), + toBytes: convertToBytes(PbFieldType.OF6), + ); roundtrip(make64(0, 0), [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); roundtrip(make64(1, 0), [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); - roundtrip(make64(0xffffffff, 0xffffffff), - [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); - roundtrip(make64(0x00000001, 0x40000000), - [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40]); + roundtrip(make64(0xffffffff, 0xffffffff), [ + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + ]); + roundtrip(make64(0x00000001, 0x40000000), [ + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x40, + ]); }); test('testSfixed32', () { final roundtrip = roundtripTester( - fromBytes: (CodedBufferReader reader) => reader.readSfixed32(), - toBytes: convertToBytes(PbFieldType.OSF3)); + fromBytes: (CodedBufferReader reader) => reader.readSfixed32(), + toBytes: convertToBytes(PbFieldType.OSF3), + ); roundtrip(0, [0x00, 0x00, 0x00, 0x00]); roundtrip(1, [0x01, 0x00, 0x00, 0x00]); @@ -104,17 +137,34 @@ void main() { test('testSfixed64', () { final roundtrip = roundtripTester( - fromBytes: (CodedBufferReader reader) => reader.readSfixed64(), - toBytes: convertToBytes(PbFieldType.OSF6)); + fromBytes: (CodedBufferReader reader) => reader.readSfixed64(), + toBytes: convertToBytes(PbFieldType.OSF6), + ); roundtrip(make64(0), [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); roundtrip(make64(-1), [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); roundtrip(make64(1), [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); roundtrip(make64(-2), [0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); - roundtrip(make64(0xffffffff, 0x7fffffff), - [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f]); - roundtrip(make64(0x00000000, 0x80000000), - [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]); + roundtrip(make64(0xffffffff, 0x7fffffff), [ + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0x7f, + ]); + roundtrip(make64(0x00000000, 0x80000000), [ + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x80, + ]); }); test('testBool', () { @@ -127,9 +177,10 @@ void main() { // Compare two doubles, where NaNs and same-sign inifinities compare equal. // For normal values, use equals. - Matcher doubleEquals(double expected) => expected.isNaN - ? predicate((x) => x.isNaN, 'NaN expected') - : equals(expected); + Matcher doubleEquals(double expected) => + expected.isNaN + ? predicate((x) => x.isNaN, 'NaN expected') + : equals(expected); List dataToBytes(ByteData byteData) => Uint8List.view(byteData.buffer); final floatToBytes = convertToBytes(PbFieldType.OF); @@ -153,7 +204,7 @@ void main() { final data = makeData(doubleToBytes(value)); final actualHilo = [ data.getUint32(4, Endian.little), - data.getUint32(0, Endian.little) + data.getUint32(0, Endian.little), ]; //int encoded = data.getUint64(0, Endian.little); expect(actualHilo, hilo); @@ -680,8 +731,9 @@ void main() { test('testVarint64', () { final roundtrip = roundtripTester( - fromBytes: (CodedBufferReader reader) => reader.readUint64(), - toBytes: convertToBytes(PbFieldType.OU6)); + fromBytes: (CodedBufferReader reader) => reader.readUint64(), + toBytes: convertToBytes(PbFieldType.OU6), + ); roundtrip(make64(0), [0x00]); roundtrip(make64(3), [0x03]); @@ -694,14 +746,51 @@ void main() { roundtrip(make64(0x9e5301), [0x81, 0xa6, 0xf9, 0x04]); roundtrip(make64(0x7fffffff), [0xff, 0xff, 0xff, 0xff, 0x07]); roundtrip(make64(0xffffffff), [0xff, 0xff, 0xff, 0xff, 0x0f]); - roundtrip(make64(0xffffffff, 0xffffff), - [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f]); - roundtrip(make64(0xffffffff, 0xffffffff), - [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]); - roundtrip(make64(0xffff2f34, 0xffffffff), - [180, 222, 252, 255, 255, 255, 255, 255, 255, 1]); - roundtrip(make64(0x00000001, 0x40000000), - [0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x40]); + roundtrip(make64(0xffffffff, 0xffffff), [ + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0x7f, + ]); + roundtrip(make64(0xffffffff, 0xffffffff), [ + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0x01, + ]); + roundtrip(make64(0xffff2f34, 0xffffffff), [ + 180, + 222, + 252, + 255, + 255, + 255, + 255, + 255, + 255, + 1, + ]); + roundtrip(make64(0x00000001, 0x40000000), [ + 0x81, + 0x80, + 0x80, + 0x80, + 0x80, + 0x80, + 0x80, + 0x80, + 0x40, + ]); }); test('testWriteTo', () { diff --git a/protobuf/test/coded_buffer_reader_test.dart b/protobuf/test/coded_buffer_reader_test.dart index 85c6ea67c..9f83d92e4 100644 --- a/protobuf/test/coded_buffer_reader_test.dart +++ b/protobuf/test/coded_buffer_reader_test.dart @@ -10,8 +10,9 @@ import 'package:test/test.dart'; import 'test_util.dart'; void main() { - final throwsInvalidProtocolBufferException = - throwsA(TypeMatcher()); + final throwsInvalidProtocolBufferException = throwsA( + TypeMatcher(), + ); group('testCodedBufferReader', () { final inputBuffer = List.unmodifiable([ @@ -33,7 +34,7 @@ void main() { 0x69, 0x6e, 0x67, // 114 string 15 optional_string 0x9a, 0x07, 0x0e, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x5f, 0x62, 0x79, 0x74, - 0x65, 0x73 // 115 bytes 14 optional_bytes + 0x65, 0x73, // 115 bytes 14 optional_bytes ]); void testWithList(List inputBuffer) { diff --git a/protobuf/test/json_test.dart b/protobuf/test/json_test.dart index 11005d072..beec88f2d 100644 --- a/protobuf/test/json_test.dart +++ b/protobuf/test/json_test.dart @@ -14,10 +14,11 @@ import 'package:test/test.dart'; import 'mock_util.dart' show T, mockEnumValues; void main() { - final example = T() - ..val = 123 - ..str = 'hello' - ..int32s.addAll([1, 2, 3]); + final example = + T() + ..val = 123 + ..str = 'hello' + ..int32s.addAll([1, 2, 3]); test('testProto3JsonEnum', () { // No enum value specified. @@ -31,11 +32,16 @@ void main() { expect((example..mergeFromProto3Json({'enm': 'b'})).enm.name, equals('b')); // "c" is not a legal enum value. expect( - () => example..mergeFromProto3Json({'enm': 'c'}), - throwsA(allOf( - isFormatException, - predicate((FormatException e) => - e.message.contains('Unknown enum value'))))); + () => example..mergeFromProto3Json({'enm': 'c'}), + throwsA( + allOf( + isFormatException, + predicate( + (FormatException e) => e.message.contains('Unknown enum value'), + ), + ), + ), + ); // `example` hasn't changed. expect(example.hasEnm, isTrue); expect(example.enm.name, equals('b')); @@ -43,20 +49,26 @@ void main() { // "c" is not a legal enum value, but we are ignoring unknown fields, so // default behavior is to unset `enm`, returning the default value "a" expect( - (example..mergeFromProto3Json({'enm': 'c'}, ignoreUnknownFields: true)) - .enm - .name, - equals('a')); + (example..mergeFromProto3Json({'enm': 'c'}, ignoreUnknownFields: true)) + .enm + .name, + equals('a'), + ); expect(example.hasEnm, isFalse); // Same for index values... expect((example..mergeFromProto3Json({'enm': 2})).enm.name, 'b'); expect( - () => example..mergeFromProto3Json({'enm': 3}), - throwsA(allOf( - isFormatException, - predicate((FormatException e) => - e.message.contains('Unknown enum value'))))); + () => example..mergeFromProto3Json({'enm': 3}), + throwsA( + allOf( + isFormatException, + predicate( + (FormatException e) => e.message.contains('Unknown enum value'), + ), + ), + ), + ); // `example` hasn't changed. expect(example.hasEnm, isTrue); expect(example.enm.name, equals('b')); @@ -64,10 +76,11 @@ void main() { // "c" is not a legal enum value, but we are ignoring unknown fields, so // default behavior is to unset `enm`, returning the default value "a" expect( - (example..mergeFromProto3Json({'enm': 3}, ignoreUnknownFields: true)) - .enm - .name, - equals('a')); + (example..mergeFromProto3Json({'enm': 3}, ignoreUnknownFields: true)) + .enm + .name, + equals('a'), + ); expect(example.hasEnm, isFalse); }); @@ -110,9 +123,10 @@ void main() { test('testFrozentInt64JsonEncoding', () { final value = Int64.parseInt('1234567890123456789'); - final frozen = T() - ..int64 = value - ..freeze(); + final frozen = + T() + ..int64 = value + ..freeze(); final encoded = frozen.writeToJsonMap(); expect(encoded['5'], '$value'); final decoded = T()..mergeFromJsonMap(encoded); diff --git a/protobuf/test/list_equality_test.dart b/protobuf/test/list_equality_test.dart index 26e238a40..00adce0a4 100644 --- a/protobuf/test/list_equality_test.dart +++ b/protobuf/test/list_equality_test.dart @@ -28,12 +28,14 @@ void main() { }); test('non-empty frozen lists compare as equal', () { - final first = T() - ..int32s.add(1) - ..freeze(); - final second = T() - ..int32s.add(1) - ..freeze(); + final first = + T() + ..int32s.add(1) + ..freeze(); + final second = + T() + ..int32s.add(1) + ..freeze(); expect(first.int32s == second.int32s, isTrue); }); @@ -44,12 +46,14 @@ void main() { }); test('different frozen lists do not compare as equal', () { - final first = T() - ..int32s.add(1) - ..freeze(); - final second = T() - ..int32s.add(2) - ..freeze(); + final first = + T() + ..int32s.add(1) + ..freeze(); + final second = + T() + ..int32s.add(2) + ..freeze(); expect(first.int32s == second.int32s, isFalse); }); } diff --git a/protobuf/test/list_test.dart b/protobuf/test/list_test.dart index 4d29ece59..23e995100 100644 --- a/protobuf/test/list_test.dart +++ b/protobuf/test/list_test.dart @@ -7,8 +7,9 @@ import 'package:protobuf/protobuf.dart'; import 'package:test/test.dart'; // [ArgumentError] in production mode, [TypeError] in checked. -final invalidArgumentException = - predicate((e) => e is ArgumentError || e is TypeError); +final invalidArgumentException = predicate( + (e) => e is ArgumentError || e is TypeError, +); final badArgument = throwsA(invalidArgumentException); // Suppress an analyzer warning for a deliberate type mismatch. @@ -103,17 +104,25 @@ void main() { list.add(-2147483649); }, throwsArgumentError); - expect(() { - list.add(-2147483648); - }, returnsNormally, reason: 'could not add min signed int32 to a PbList'); + expect( + () { + list.add(-2147483648); + }, + returnsNormally, + reason: 'could not add min signed int32 to a PbList', + ); expect(() { list.add(2147483648); }, throwsArgumentError); - expect(() { - list.add(2147483647); - }, returnsNormally, reason: 'could not add max signed int32 to a PbList'); + expect( + () { + list.add(2147483647); + }, + returnsNormally, + reason: 'could not add max signed int32 to a PbList', + ); }); test('PBList for unsigned int32 validates items', () { @@ -123,17 +132,25 @@ void main() { list.add(-1); }, throwsArgumentError); - expect(() { - list.add(0); - }, returnsNormally, reason: 'could not add zero to a PbList'); + expect( + () { + list.add(0); + }, + returnsNormally, + reason: 'could not add zero to a PbList', + ); expect(() { list.add(4294967296); }, throwsArgumentError); - expect(() { - list.add(4294967295); - }, returnsNormally, reason: 'could not add max unsigned int32 to a PbList'); + expect( + () { + list.add(4294967295); + }, + returnsNormally, + reason: 'could not add max unsigned int32 to a PbList', + ); }); test('PbList for float validates items', () { @@ -147,13 +164,21 @@ void main() { list.add(-3.4028234663852886E39); }, throwsArgumentError); - expect(() { - list.add(3.4028234663852886E38); - }, returnsNormally, reason: 'could not add max float to a PbList'); - - expect(() { - list.add(-3.4028234663852886E38); - }, returnsNormally, reason: 'could not add min float to a PbList'); + expect( + () { + list.add(3.4028234663852886E38); + }, + returnsNormally, + reason: 'could not add max float to a PbList', + ); + + expect( + () { + list.add(-3.4028234663852886E38); + }, + returnsNormally, + reason: 'could not add min float to a PbList', + ); }); test('PbList for signed Int64 validates items', () { @@ -162,17 +187,29 @@ void main() { list.add(cast(0)); // not an Int64 }, badArgument); - expect(() { - list.add(Int64(0)); - }, returnsNormally, reason: 'could not add Int64(0) to a PbList'); - - expect(() { - list.add(Int64.MAX_VALUE); - }, returnsNormally, reason: 'could not add max Int64 to a PbList'); - - expect(() { - list.add(Int64.MIN_VALUE); - }, returnsNormally, reason: 'could not add min Int64 to PbList'); + expect( + () { + list.add(Int64(0)); + }, + returnsNormally, + reason: 'could not add Int64(0) to a PbList', + ); + + expect( + () { + list.add(Int64.MAX_VALUE); + }, + returnsNormally, + reason: 'could not add max Int64 to a PbList', + ); + + expect( + () { + list.add(Int64.MIN_VALUE); + }, + returnsNormally, + reason: 'could not add min Int64 to PbList', + ); }); test('PbList for unsigned Int64 validates items', () { @@ -181,23 +218,39 @@ void main() { list.add(cast(0)); // not an Int64 }, badArgument); - expect(() { - list.add(Int64(0)); - }, returnsNormally, reason: 'could not add Int64(0) to a PbList'); + expect( + () { + list.add(Int64(0)); + }, + returnsNormally, + reason: 'could not add Int64(0) to a PbList', + ); // Adding -1 should work because we are storing the bits as-is. // (It will be interpreted as a positive number.) // See: https://github.com/google/protobuf.dart/issues/44 - expect(() { - list.add(Int64(-1)); - }, returnsNormally, reason: 'could not add Int64(-1) to a PbList'); - - expect(() { - list.add(Int64.MAX_VALUE); - }, returnsNormally, reason: 'could not add max Int64 to a PbList'); - - expect(() { - list.add(Int64.MIN_VALUE); - }, returnsNormally, reason: 'could not add min Int64 to a PbList'); + expect( + () { + list.add(Int64(-1)); + }, + returnsNormally, + reason: 'could not add Int64(-1) to a PbList', + ); + + expect( + () { + list.add(Int64.MAX_VALUE); + }, + returnsNormally, + reason: 'could not add max Int64 to a PbList', + ); + + expect( + () { + list.add(Int64.MIN_VALUE); + }, + returnsNormally, + reason: 'could not add min Int64 to a PbList', + ); }); } diff --git a/protobuf/test/message_test.dart b/protobuf/test/message_test.dart index bdecbcd0f..24a40304a 100644 --- a/protobuf/test/message_test.dart +++ b/protobuf/test/message_test.dart @@ -17,8 +17,9 @@ class Rec extends MockMessage { Rec createEmptyInstance() => Rec(); } -Matcher throwsError(String expectedMessage) => throwsA(isA() - .having((p0) => p0.message, 'message', expectedMessage)); +Matcher throwsError(String expectedMessage) => throwsA( + isA().having((p0) => p0.message, 'message', expectedMessage), +); void main() { test('getField with invalid tag throws exception', () { @@ -36,13 +37,15 @@ void main() { }); test('operator== and hashCode works for frozen message', () { - final a = Rec() - ..val = 123 - ..int32s.addAll([1, 2, 3]) - ..freeze(); - final b = Rec() - ..val = 123 - ..int32s.addAll([1, 2, 3]); + final a = + Rec() + ..val = 123 + ..int32s.addAll([1, 2, 3]) + ..freeze(); + final b = + Rec() + ..val = 123 + ..int32s.addAll([1, 2, 3]); expect(a.hashCode, b.hashCode); expect(a == b, true); @@ -50,10 +53,11 @@ void main() { }); test('isFrozen works', () { - final a = Rec() - ..val = 123 - ..int32s.addAll([1, 2, 3]) - ..child = (Rec()..val = 100); + final a = + Rec() + ..val = 123 + ..int32s.addAll([1, 2, 3]) + ..child = (Rec()..val = 100); expect(a.isFrozen, false); a.child.freeze(); expect(a.child.isFrozen, true); diff --git a/protobuf/test/mock_util.dart b/protobuf/test/mock_util.dart index 731763547..fdd385ea3 100644 --- a/protobuf/test/mock_util.dart +++ b/protobuf/test/mock_util.dart @@ -21,10 +21,14 @@ BuilderInfo mockInfo(String className, CreateBuilderFunc create) { ..p(4, 'int32s', PbFieldType.P3) ..a(5, 'int64', PbFieldType.O6) // 6 is reserved for extensions in other tests. - ..e(7, 'enm', PbFieldType.OE, - defaultOrMaker: mockEnumValues.first, - valueOf: (i) => mockEnumValues.firstWhereOrNull((e) => e.value == i), - enumValues: mockEnumValues); + ..e( + 7, + 'enm', + PbFieldType.OE, + defaultOrMaker: mockEnumValues.first, + valueOf: (i) => mockEnumValues.firstWhereOrNull((e) => e.value == i), + enumValues: mockEnumValues, + ); } /// A minimal protobuf implementation for testing. diff --git a/protobuf/test/readonly_message_test.dart b/protobuf/test/readonly_message_test.dart index 335fda650..cf5b37d59 100644 --- a/protobuf/test/readonly_message_test.dart +++ b/protobuf/test/readonly_message_test.dart @@ -7,9 +7,12 @@ import 'package:protobuf/protobuf.dart' import 'package:test/test.dart'; Matcher throwsUnsupportedError(Matcher expectedMessage) => throwsA( - isA() - .having((p0) => p0.message, 'message', expectedMessage), - ); + isA().having( + (p0) => p0.message, + 'message', + expectedMessage, + ), +); class Rec extends GeneratedMessage { static Rec getDefault() => Rec()..freeze(); @@ -18,10 +21,11 @@ class Rec extends GeneratedMessage { Rec createEmptyInstance() => Rec(); @override - BuilderInfo info_ = BuilderInfo('rec') - ..a(1, 'value', PbFieldType.O3) - ..pc(2, 'sub', PbFieldType.PM, subBuilder: Rec.create) - ..p(10, 'ints', PbFieldType.P3); + BuilderInfo info_ = + BuilderInfo('rec') + ..a(1, 'value', PbFieldType.O3) + ..pc(2, 'sub', PbFieldType.PM, subBuilder: Rec.create) + ..p(10, 'ints', PbFieldType.P3); int get value => $_get(0, 0); set value(int v) { @@ -53,77 +57,107 @@ void main() { test("can't merge to a read-only message", () { expect( - () => Rec.getDefault().mergeFromJson('{"1":1}'), - throwsUnsupportedError( - equals('Attempted to change a read-only message (rec)'))); + () => Rec.getDefault().mergeFromJson('{"1":1}'), + throwsUnsupportedError( + equals('Attempted to change a read-only message (rec)'), + ), + ); }); test("can't set a field on a read-only message", () { expect( - () => Rec.getDefault().setField(1, 456), - throwsUnsupportedError( - equals('Attempted to change a read-only message (rec)'))); + () => Rec.getDefault().setField(1, 456), + throwsUnsupportedError( + equals('Attempted to change a read-only message (rec)'), + ), + ); }); test("can't clear a read-only message", () { expect( - () => Rec.getDefault().clear(), - throwsUnsupportedError( - equals('Attempted to change a read-only message (rec)'))); + () => Rec.getDefault().clear(), + throwsUnsupportedError( + equals('Attempted to change a read-only message (rec)'), + ), + ); }); test("can't clear a field on a read-only message", () { expect( - () => Rec.getDefault().clearField(1), - throwsUnsupportedError( - equals('Attempted to change a read-only message (rec)'))); + () => Rec.getDefault().clearField(1), + throwsUnsupportedError( + equals('Attempted to change a read-only message (rec)'), + ), + ); }); test("can't modify repeated fields on a read-only message", () { - expect(() => Rec.getDefault().sub.add(Rec.create()), - throwsUnsupportedError(contains('add'))); - var r = Rec.create() - ..ints.add(10) - ..freeze(); - expect(() => r.ints.clear(), - throwsUnsupportedError(equals("'clear' on a read-only list"))); - expect(() => r.ints[0] = 2, - throwsUnsupportedError(equals("'set element' on a read-only list"))); - expect(() => r.sub.add(Rec.create()), - throwsUnsupportedError(equals("'add' on a read-only list"))); - - r = Rec.create() - ..sub.add(Rec.create()) - ..freeze(); - expect(() => r.sub.add(Rec.create()), - throwsUnsupportedError(equals("'add' on a read-only list"))); expect( - () => r.ints.length = 20, throwsUnsupportedError(contains('length'))); + () => Rec.getDefault().sub.add(Rec.create()), + throwsUnsupportedError(contains('add')), + ); + var r = + Rec.create() + ..ints.add(10) + ..freeze(); + expect( + () => r.ints.clear(), + throwsUnsupportedError(equals("'clear' on a read-only list")), + ); + expect( + () => r.ints[0] = 2, + throwsUnsupportedError(equals("'set element' on a read-only list")), + ); + expect( + () => r.sub.add(Rec.create()), + throwsUnsupportedError(equals("'add' on a read-only list")), + ); + + r = + Rec.create() + ..sub.add(Rec.create()) + ..freeze(); + expect( + () => r.sub.add(Rec.create()), + throwsUnsupportedError(equals("'add' on a read-only list")), + ); + expect( + () => r.ints.length = 20, + throwsUnsupportedError(contains('length')), + ); }); test("can't modify sub-messages on a read-only message", () { final subMessage = Rec.create()..value = 1; - final r = Rec.create() - ..sub.add(Rec.create()..sub.add(subMessage)) - ..freeze(); + final r = + Rec.create() + ..sub.add(Rec.create()..sub.add(subMessage)) + ..freeze(); expect(r.sub[0].sub[0].value, 1); expect( - () => subMessage.value = 2, - throwsUnsupportedError( - equals('Attempted to change a read-only message (rec)'))); + () => subMessage.value = 2, + throwsUnsupportedError( + equals('Attempted to change a read-only message (rec)'), + ), + ); }); test("can't modify unknown fields on a read-only message", () { expect( - () => Rec.getDefault().unknownFields.clear(), - throwsUnsupportedError(equals( - 'Attempted to call clear on a read-only message (UnknownFieldSet)'))); + () => Rec.getDefault().unknownFields.clear(), + throwsUnsupportedError( + equals( + 'Attempted to call clear on a read-only message (UnknownFieldSet)', + ), + ), + ); }); test('can rebuild a frozen message with merge', () { - final orig = Rec.create() - ..value = 10 - ..freeze(); + final orig = + Rec.create() + ..value = 10 + ..freeze(); final rebuilt = orig.copyWith((m) => m.mergeFromJson('{"1": 7}')); expect(identical(orig, rebuilt), false); expect(orig.value, 10); @@ -131,9 +165,10 @@ void main() { }); test('can set a field while rebuilding a frozen message', () { - final orig = Rec.create() - ..value = 10 - ..freeze(); + final orig = + Rec.create() + ..value = 10 + ..freeze(); final rebuilt = orig.copyWith((m) => m.value = 7); expect(identical(orig, rebuilt), false); expect(orig.value, 10); @@ -141,9 +176,10 @@ void main() { }); test('can clear while rebuilding a frozen message', () { - final orig = Rec.create() - ..value = 10 - ..freeze(); + final orig = + Rec.create() + ..value = 10 + ..freeze(); final rebuilt = orig.copyWith((m) => m.clear()); expect(identical(orig, rebuilt), false); expect(orig.value, 10); @@ -152,9 +188,10 @@ void main() { }); test('can clear a field while rebuilding a frozen message', () { - final orig = Rec.create() - ..value = 10 - ..freeze(); + final orig = + Rec.create() + ..value = 10 + ..freeze(); final rebuilt = orig.copyWith((m) => m.clearField(1)); expect(identical(orig, rebuilt), false); expect(orig.value, 10); @@ -163,9 +200,10 @@ void main() { }); test('can modify repeated fields while rebuilding a frozen message', () { - var orig = Rec.create() - ..ints.add(10) - ..freeze(); + var orig = + Rec.create() + ..ints.add(10) + ..freeze(); var rebuilt = orig.copyWith((m) => m.ints.add(12)); expect(identical(orig, rebuilt), false); expect(orig.ints, [10]); @@ -179,9 +217,10 @@ void main() { expect(orig.ints, [10]); expect(rebuilt.ints, [2]); - orig = Rec.create() - ..sub.add(Rec.create()) - ..freeze(); + orig = + Rec.create() + ..sub.add(Rec.create()) + ..freeze(); rebuilt = orig.copyWith((m) => m.sub.add(Rec.create())); expect(orig.sub.length, 1); expect(rebuilt.sub.length, 2); @@ -189,21 +228,27 @@ void main() { test('cannot modify sub-messages while rebuilding a frozen message', () { final subMessage = Rec.create()..value = 1; - final orig = Rec.create() - ..sub.add(Rec.create()..sub.add(subMessage)) - ..freeze(); + final orig = + Rec.create() + ..sub.add(Rec.create()..sub.add(subMessage)) + ..freeze(); final rebuilt = orig.copyWith((m) { expect( - () => subMessage.value = 5, - throwsUnsupportedError( - equals('Attempted to change a read-only message (rec)'))); + () => subMessage.value = 5, + throwsUnsupportedError( + equals('Attempted to change a read-only message (rec)'), + ), + ); expect( - () => m.sub[0].sub[0].value = 2, - throwsUnsupportedError( - equals('Attempted to change a read-only message (rec)'))); + () => m.sub[0].sub[0].value = 2, + throwsUnsupportedError( + equals('Attempted to change a read-only message (rec)'), + ), + ); m.sub[0] = m.sub[0].copyWith( - (m2) => m2.sub[0] = m2.sub[0].copyWith((m3) => m3.value = 2)); + (m2) => m2.sub[0] = m2.sub[0].copyWith((m3) => m3.value = 2), + ); }); expect(identical(subMessage, orig.sub[0].sub[0]), true); expect(identical(subMessage, rebuilt.sub[0].sub[0]), false); @@ -212,8 +257,9 @@ void main() { }); test('can modify unknown fields while rebuilding a frozen message', () { - final orig = Rec.create() - ..unknownFields.addField(20, UnknownFieldSetField()..fixed32s.add(1)); + final orig = + Rec.create() + ..unknownFields.addField(20, UnknownFieldSetField()..fixed32s.add(1)); final rebuilt = orig.copyWith((m) => m.unknownFields.clear()); expect(orig.unknownFields.hasField(20), true); expect(rebuilt.unknownFields.hasField(20), false); diff --git a/protoc_plugin/CHANGELOG.md b/protoc_plugin/CHANGELOG.md index 62feef009..9bfa74ad5 100644 --- a/protoc_plugin/CHANGELOG.md +++ b/protoc_plugin/CHANGELOG.md @@ -1,3 +1,9 @@ +## 22.4.1-wip + +* Minimum SDK dependency bumped from 3.6.0 to 3.7.0. ([#1024]) + +[#1024]: https://github.com/google/protobuf.dart/pull/1024 + ## 22.4.0 * Update how we calculate import prefixes ([#1010]); import prefixes are now diff --git a/protoc_plugin/bin/protoc_plugin_bazel.dart b/protoc_plugin/bin/protoc_plugin_bazel.dart index 4865e1556..c6dd2a6ba 100755 --- a/protoc_plugin/bin/protoc_plugin_bazel.dart +++ b/protoc_plugin/bin/protoc_plugin_bazel.dart @@ -11,6 +11,7 @@ import 'package:protoc_plugin/protoc.dart'; void main() { final packages = {}; CodeGenerator(stdin, stdout).generate( - optionParsers: {bazelOptionId: BazelOptionParser(packages)}, - config: BazelOutputConfiguration(packages)); + optionParsers: {bazelOptionId: BazelOptionParser(packages)}, + config: BazelOutputConfiguration(packages), + ); } diff --git a/protoc_plugin/lib/bazel.dart b/protoc_plugin/lib/bazel.dart index 24fc289bf..c0c76898a 100644 --- a/protoc_plugin/lib/bazel.dart +++ b/protoc_plugin/lib/bazel.dart @@ -33,8 +33,8 @@ class BazelPackage { final String outputRoot; BazelPackage(this.name, String inputRoot, String outputRoot) - : inputRoot = p.normalize(inputRoot), - outputRoot = p.normalize(outputRoot); + : inputRoot = p.normalize(inputRoot), + outputRoot = p.normalize(outputRoot); } /// Parser for the `BazelPackages` option. @@ -55,7 +55,8 @@ class BazelOptionParser implements SingleOptionParser { final fields = entry.split('|'); if (fields.length != 3) { onError( - 'ERROR: expected package_name|input_root|output_root. Got: $entry'); + 'ERROR: expected package_name|input_root|output_root. Got: $entry', + ); continue; } final pkg = BazelPackage(fields[0], fields[1], fields[2]); @@ -64,13 +65,17 @@ class BazelOptionParser implements SingleOptionParser { } else { final prev = output[pkg.inputRoot]!; if (pkg.name != prev.name) { - onError('ERROR: multiple packages with input_root ${pkg.inputRoot}: ' - '${prev.name} and ${pkg.name}'); + onError( + 'ERROR: multiple packages with input_root ${pkg.inputRoot}: ' + '${prev.name} and ${pkg.name}', + ); continue; } if (pkg.outputRoot != prev.outputRoot) { - onError('ERROR: conflicting output_roots for package ${pkg.name}: ' - '${prev.outputRoot} and ${pkg.outputRoot}'); + onError( + 'ERROR: conflicting output_roots for package ${pkg.name}: ' + '${prev.outputRoot} and ${pkg.outputRoot}', + ); continue; } } diff --git a/protoc_plugin/lib/const_generator.dart b/protoc_plugin/lib/const_generator.dart index e9415db39..bb8e6b14a 100644 --- a/protoc_plugin/lib/const_generator.dart +++ b/protoc_plugin/lib/const_generator.dart @@ -10,8 +10,12 @@ import 'string_escape.dart'; void writeJsonConst(IndentingWriter out, Object? val) { if (val is Map) { if (val.values.any(_nonEmptyListOrMap)) { - out.addBlock('{', '}', () => _writeMapItems(out, val, vertical: true), - endWithNewline: false); + out.addBlock( + '{', + '}', + () => _writeMapItems(out, val, vertical: true), + endWithNewline: false, + ); } else { out.print('{'); _writeMapItems(out, val); @@ -19,8 +23,12 @@ void writeJsonConst(IndentingWriter out, Object? val) { } } else if (val is List) { if (val.any(_nonEmptyListOrMap)) { - out.addBlock('[', ']', () => _writeListItems(out, val, vertical: true), - endWithNewline: false); + out.addBlock( + '[', + ']', + () => _writeListItems(out, val, vertical: true), + endWithNewline: false, + ); } else { out.print('['); _writeListItems(out, val); @@ -61,8 +69,11 @@ void _writeListItems(IndentingWriter out, List val, {bool vertical = false}) { } } -void _writeMapItems(IndentingWriter out, Map val, - {bool vertical = false}) { +void _writeMapItems( + IndentingWriter out, + Map val, { + bool vertical = false, +}) { var first = true; for (final key in val.keys) { if (!first && !vertical) out.print(', '); diff --git a/protoc_plugin/lib/indenting_writer.dart b/protoc_plugin/lib/indenting_writer.dart index b2b5808ff..2bf213895 100644 --- a/protoc_plugin/lib/indenting_writer.dart +++ b/protoc_plugin/lib/indenting_writer.dart @@ -13,10 +13,11 @@ class NamedLocation { final List fieldPathSegment; final int start; - NamedLocation( - {required this.name, - required this.fieldPathSegment, - required this.start}); + NamedLocation({ + required this.name, + required this.fieldPathSegment, + required this.start, + }); } /// A buffer for writing indented source code. @@ -63,8 +64,11 @@ class IndentingWriter { final indentOffset = _needIndent ? _indent.length : 0; print(text); for (final location in namedLocations) { - _addAnnotation(location.fieldPathSegment, location.name, - location.start + indentOffset); + _addAnnotation( + location.fieldPathSegment, + location.name, + location.start + indentOffset, + ); } } @@ -74,29 +78,45 @@ class IndentingWriter { } /// Prints a block of text with the body indented one more level. - void addBlock(String start, String end, void Function() body, - {bool endWithNewline = true}) { + void addBlock( + String start, + String end, + void Function() body, { + bool endWithNewline = true, + }) { println(start); _addBlockBodyAndEnd(end, body, endWithNewline, '$_indent '); } /// Prints a block of text with an unindented body. /// (For example, for triple quotes.) - void addUnindentedBlock(String start, String end, void Function() body, - {bool endWithNewline = true}) { + void addUnindentedBlock( + String start, + String end, + void Function() body, { + bool endWithNewline = true, + }) { println(start); _addBlockBodyAndEnd(end, body, endWithNewline, ''); } - void addAnnotatedBlock(String start, String end, - List namedLocations, void Function() body, - {bool endWithNewline = true}) { + void addAnnotatedBlock( + String start, + String end, + List namedLocations, + void Function() body, { + bool endWithNewline = true, + }) { printlnAnnotated(start, namedLocations); _addBlockBodyAndEnd(end, body, endWithNewline, '$_indent '); } void _addBlockBodyAndEnd( - String end, void Function() body, bool endWithNewline, String newIndent) { + String end, + void Function() body, + bool endWithNewline, + String newIndent, + ) { final oldIndent = _indent; _indent = newIndent; body(); @@ -158,11 +178,12 @@ class IndentingWriter { if (_sourceFile == null) { return; } - final annotation = GeneratedCodeInfo_Annotation() - ..path.addAll(fieldPath) - ..sourceFile = _sourceFile - ..begin = _previousOffset + start - ..end = _previousOffset + start + name.length; + final annotation = + GeneratedCodeInfo_Annotation() + ..path.addAll(fieldPath) + ..sourceFile = _sourceFile + ..begin = _previousOffset + start + ..end = _previousOffset + start + name.length; sourceLocationInfo.annotation.add(annotation); } } @@ -203,9 +224,10 @@ class ImportWriter { /// And an export. void addExport(String url, {List members = const []}) { - final directive = members.isNotEmpty - ? "export '$url' show ${members.join(', ')};" - : "export '$url';"; + final directive = + members.isNotEmpty + ? "export '$url' show ${members.join(', ')};" + : "export '$url';"; if (url.startsWith('package:')) { _packageExports.add(directive); } else { diff --git a/protoc_plugin/lib/mixins.dart b/protoc_plugin/lib/mixins.dart index ee04fbf33..6d9691586 100644 --- a/protoc_plugin/lib/mixins.dart +++ b/protoc_plugin/lib/mixins.dart @@ -10,9 +10,7 @@ import 'indenting_writer.dart'; /// Finds [name] in the exported mixins. PbMixin? findMixin(String name) { - const exportedMixins = { - 'PbMapMixin': _pbMapMixin, - }; + const exportedMixins = {'PbMapMixin': _pbMapMixin}; return exportedMixins[name]; } @@ -81,9 +79,11 @@ class PbMixin { } } -const _pbMapMixin = PbMixin('PbMapMixin', - importFrom: 'package:protobuf/src/protobuf/mixins/map_mixin.dart', - parent: _mapMixin); +const _pbMapMixin = PbMixin( + 'PbMapMixin', + importFrom: 'package:protobuf/src/protobuf/mixins/map_mixin.dart', + parent: _mapMixin, +); const List _reservedNamesForMap = [ '[]', @@ -109,5 +109,8 @@ const List _reservedNamesForMap = [ 'values', ]; -const _mapMixin = PbMixin('MapMixin', - importFrom: 'dart:collection', reservedNames: _reservedNamesForMap); +const _mapMixin = PbMixin( + 'MapMixin', + importFrom: 'dart:collection', + reservedNames: _reservedNamesForMap, +); diff --git a/protoc_plugin/lib/names.dart b/protoc_plugin/lib/names.dart index 52460c470..cf176a70e 100644 --- a/protoc_plugin/lib/names.dart +++ b/protoc_plugin/lib/names.dart @@ -50,8 +50,15 @@ class FieldNames { // `null` for scalar, repeated, and map fields. final String? ensureMethodName; - FieldNames(this.descriptor, this.index, this.sourcePosition, this.fieldName, - {this.hasMethodName, this.clearMethodName, this.ensureMethodName}); + FieldNames( + this.descriptor, + this.index, + this.sourcePosition, + this.fieldName, { + this.hasMethodName, + this.clearMethodName, + this.ensureMethodName, + }); } /// The Dart names associated with a oneof declaration. @@ -73,8 +80,14 @@ class OneofNames { /// Identifier for the _XByTag map. final String byTagMapName; - OneofNames(this.descriptor, this.index, this.clearMethodName, - this.whichOneofMethodName, this.oneofEnumName, this.byTagMapName); + OneofNames( + this.descriptor, + this.index, + this.clearMethodName, + this.whichOneofMethodName, + this.oneofEnumName, + this.byTagMapName, + ); } // For performance reasons, use code units instead of Regex. @@ -127,9 +140,12 @@ String legalDartIdentifier(String input) { /// Chooses the name of the Dart class holding top-level extensions. String extensionClassName( - FileDescriptorProto descriptor, Set usedNames) { + FileDescriptorProto descriptor, + Set usedNames, +) { final s = avoidInitialUnderscore( - legalDartIdentifier(_fileNameWithoutExtension(descriptor))); + legalDartIdentifier(_fileNameWithoutExtension(descriptor)), + ); final candidate = '${s[0].toUpperCase()}${s.substring(1)}'; return disambiguateName(candidate, usedNames, extensionSuffixes()); } @@ -159,8 +175,11 @@ class DartNameOptionException implements Exception { /// [usedNames]. /// The returned name is that, which will generate the accepted variants. String disambiguateName( - String name, Set usedNames, Iterable suffixes, - {List Function(String candidate)? generateVariants}) { + String name, + Set usedNames, + Iterable suffixes, { + List Function(String candidate)? generateVariants, +}) { generateVariants ??= (String name) => [name]; bool allVariantsAvailable(List variants) { @@ -194,34 +213,50 @@ Iterable defaultSuffixes() sync* { } String oneofEnumClassName( - String descriptorName, Set usedNames, String parentName) { + String descriptorName, + Set usedNames, + String parentName, +) { descriptorName = '${parentName}_${underscoresToCamelCase(descriptorName)}'; return disambiguateName( - avoidInitialUnderscore(descriptorName), usedNames, defaultSuffixes()); + avoidInitialUnderscore(descriptorName), + usedNames, + defaultSuffixes(), + ); } String oneofEnumMemberName(String fieldName) => disambiguateName( - fieldName, Set.from(_oneofEnumMemberNames), defaultSuffixes()); + fieldName, + Set.from(_oneofEnumMemberNames), + defaultSuffixes(), +); /// Chooses the name of the Dart class to generate for a proto message or enum. /// /// For a nested message or enum, [parent] should be provided /// with the name of the Dart class for the immediate parent. -String messageOrEnumClassName(String descriptorName, Set usedNames, - {String parent = ''}) { +String messageOrEnumClassName( + String descriptorName, + Set usedNames, { + String parent = '', +}) { if (parent != '') { descriptorName = '${parent}_$descriptorName'; } return disambiguateName( - avoidInitialUnderscore(descriptorName), usedNames, defaultSuffixes()); + avoidInitialUnderscore(descriptorName), + usedNames, + defaultSuffixes(), + ); } /// Returns the set of names reserved by the ProtobufEnum class and its /// generated subclasses. -Set get reservedEnumNames => {} - ..addAll(ProtobufEnum_reservedNames) - ..addAll(_dartReservedWords) - ..addAll(_protobufEnumNames); +Set get reservedEnumNames => + {} + ..addAll(ProtobufEnum_reservedNames) + ..addAll(_dartReservedWords) + ..addAll(_protobufEnumNames); Iterable enumSuffixes() sync* { var s = '_'; @@ -241,18 +276,22 @@ Iterable enumSuffixes() sync* { /// /// Throws [DartNameOptionException] if a field has this option and /// it's set to an invalid name. -MemberNames messageMemberNames(DescriptorProto descriptor, - String parentClassName, Set usedTopLevelNames, - {Iterable reserved = const []}) { +MemberNames messageMemberNames( + DescriptorProto descriptor, + String parentClassName, + Set usedTopLevelNames, { + Iterable reserved = const [], +}) { final fieldList = List.from(descriptor.field); - final sourcePositions = - fieldList.asMap().map((index, field) => MapEntry(field.name, index)); - final sorted = fieldList - ..sort((FieldDescriptorProto a, FieldDescriptorProto b) { - if (a.number < b.number) return -1; - if (a.number > b.number) return 1; - throw 'multiple fields defined for tag ${a.number} in ${descriptor.name}'; - }); + final sourcePositions = fieldList.asMap().map( + (index, field) => MapEntry(field.name, index), + ); + final sorted = + fieldList..sort((FieldDescriptorProto a, FieldDescriptorProto b) { + if (a.number < b.number) return -1; + if (a.number > b.number) return 1; + throw 'multiple fields defined for tag ${a.number} in ${descriptor.name}'; + }); // Choose indexes first, based on their position in the sorted list. final indexes = {}; @@ -282,8 +321,15 @@ MemberNames messageMemberNames(DescriptorProto descriptor, // Explicitly setting a name that's already taken is a build error. for (final field in sorted) { if (_nameOption(field)!.isNotEmpty) { - takeFieldNames(_memberNamesFromOption(descriptor, field, - indexes[field.name]!, sourcePositions[field.name]!, existingNames)); + takeFieldNames( + _memberNamesFromOption( + descriptor, + field, + indexes[field.name]!, + sourcePositions[field.name]!, + existingNames, + ), + ); } } @@ -294,7 +340,8 @@ MemberNames messageMemberNames(DescriptorProto descriptor, final index = indexes[field.name]!; final sourcePosition = sourcePositions[field.name]; takeFieldNames( - _unusedMemberNames(field, index, sourcePosition, existingNames)); + _unusedMemberNames(field, index, sourcePosition, existingNames), + ); } } @@ -316,17 +363,34 @@ MemberNames messageMemberNames(DescriptorProto descriptor, final oneof = descriptor.oneofDecl[i]; final oneofName = disambiguateName( - underscoresToCamelCase(oneof.name), existingNames, defaultSuffixes(), - generateVariants: oneofNameVariants); - - final oneofEnumName = - oneofEnumClassName(oneof.name, usedTopLevelNames, parentClassName); + underscoresToCamelCase(oneof.name), + existingNames, + defaultSuffixes(), + generateVariants: oneofNameVariants, + ); + + final oneofEnumName = oneofEnumClassName( + oneof.name, + usedTopLevelNames, + parentClassName, + ); final enumMapName = disambiguateName( - '_${oneofEnumName}ByTag', existingNames, defaultSuffixes()); - - takeOneofNames(OneofNames(oneof, i, _defaultClearMethodName(oneofName), - _defaultWhichMethodName(oneofName), oneofEnumName, enumMapName)); + '_${oneofEnumName}ByTag', + existingNames, + defaultSuffixes(), + ); + + takeOneofNames( + OneofNames( + oneof, + i, + _defaultClearMethodName(oneofName), + _defaultWhichMethodName(oneofName), + oneofEnumName, + enumMapName, + ), + ); } return MemberNames(fieldNames.cast(), oneofNames); @@ -337,18 +401,20 @@ MemberNames messageMemberNames(DescriptorProto descriptor, /// If the explicitly-set Dart name is already taken, throw an exception. /// (Fails the build.) FieldNames _memberNamesFromOption( - DescriptorProto message, - FieldDescriptorProto field, - int index, - int sourcePosition, - Set existingNames) { + DescriptorProto message, + FieldDescriptorProto field, + int index, + int sourcePosition, + Set existingNames, +) { // TODO(skybrian): provide more context in errors (filename). final where = '${message.name}.${field.name}'; void checkAvailable(String name) { if (existingNames.contains(name)) { throw DartNameOptionException( - "$where: dart_name option is invalid: '$name' is already used"); + "$where: dart_name option is invalid: '$name' is already used", + ); } } @@ -357,8 +423,10 @@ FieldNames _memberNamesFromOption( throw ArgumentError("field doesn't have dart_name option"); } if (!_isDartFieldName(name)) { - throw DartNameOptionException('$where: dart_name option is invalid: ' - "'$name' is not a valid Dart field name"); + throw DartNameOptionException( + '$where: dart_name option is invalid: ' + "'$name' is not a valid Dart field name", + ); } checkAvailable(name); @@ -378,10 +446,15 @@ FieldNames _memberNamesFromOption( ensureMethod = 'ensure${_capitalize(name)}'; checkAvailable(ensureMethod); } - return FieldNames(field, index, sourcePosition, name, - hasMethodName: hasMethod, - clearMethodName: clearMethod, - ensureMethodName: ensureMethod); + return FieldNames( + field, + index, + sourcePosition, + name, + hasMethodName: hasMethod, + clearMethodName: clearMethod, + ensureMethodName: ensureMethod, + ); } Iterable _memberNamesSuffix(int number) sync* { @@ -392,15 +465,23 @@ Iterable _memberNamesSuffix(int number) sync* { } } -FieldNames _unusedMemberNames(FieldDescriptorProto field, int? index, - int? sourcePosition, Set existingNames) { +FieldNames _unusedMemberNames( + FieldDescriptorProto field, + int? index, + int? sourcePosition, + Set existingNames, +) { if (_isRepeated(field)) { return FieldNames( - field, - index, - sourcePosition, - disambiguateName(_defaultFieldName(_fieldMethodSuffix(field)), - existingNames, _memberNamesSuffix(field.number))); + field, + index, + sourcePosition, + disambiguateName( + _defaultFieldName(_fieldMethodSuffix(field)), + existingNames, + _memberNamesSuffix(field.number), + ), + ); } List generateNameVariants(String name) { @@ -416,16 +497,23 @@ FieldNames _unusedMemberNames(FieldDescriptorProto field, int? index, return result; } - final name = disambiguateName(_fieldMethodSuffix(field), existingNames, - _memberNamesSuffix(field.number), - generateVariants: generateNameVariants); - - return FieldNames(field, index, sourcePosition, - avoidInitialUnderscore(_defaultFieldName(name)), - hasMethodName: _defaultHasMethodName(name), - clearMethodName: _defaultClearMethodName(name), - ensureMethodName: - _isGroupOrMessage(field) ? _defaultEnsureMethodName(name) : null); + final name = disambiguateName( + _fieldMethodSuffix(field), + existingNames, + _memberNamesSuffix(field.number), + generateVariants: generateNameVariants, + ); + + return FieldNames( + field, + index, + sourcePosition, + avoidInitialUnderscore(_defaultFieldName(name)), + hasMethodName: _defaultHasMethodName(name), + clearMethodName: _defaultClearMethodName(name), + ensureMethodName: + _isGroupOrMessage(field) ? _defaultEnsureMethodName(name) : null, + ); } /// The name to use by default for the Dart getter and setter. @@ -495,13 +583,13 @@ final List forbiddenTopLevelNames = [ final List reservedMemberNames = [ ..._dartReservedWords, ...GeneratedMessage_reservedNames, - ..._generatedMessageNames + ..._generatedMessageNames, ]; final List forbiddenExtensionNames = [ ..._dartReservedWords, ...GeneratedMessage_reservedNames, - ..._generatedMessageNames + ..._generatedMessageNames, ]; // List of Dart language reserved words in names which cannot be used in a @@ -542,7 +630,7 @@ const List _dartReservedWords = [ 'var', 'void', 'while', - 'with' + 'with', ]; // List of names used in the generated message classes. @@ -554,18 +642,14 @@ const _generatedMessageNames = [ 'createRepeated', 'getDefault', 'List', - 'notSet' + 'notSet', ]; // List of names used in the generated enum classes. // // This is in addition to ProtobufEnum_reservedNames, which are names from the // base ProtobufEnum class determined by reflection. -const _protobufEnumNames = [ - 'List', - 'valueOf', - 'values', -]; +const _protobufEnumNames = ['List', 'valueOf', 'values']; // List of names used in Dart enums, which can't be used as enum member names. const _oneofEnumMemberNames = ['default', 'index', 'values']; diff --git a/protoc_plugin/lib/src/base_type.dart b/protoc_plugin/lib/src/base_type.dart index a23ed9783..0f5d08c60 100644 --- a/protoc_plugin/lib/src/base_type.dart +++ b/protoc_plugin/lib/src/base_type.dart @@ -23,8 +23,13 @@ class BaseType { // (Null for primitive types.) final ProtobufContainer? generator; - const BaseType._raw(this.descriptor, this.typeConstantSuffix, this.unprefixed, - this.setter, this.generator); + const BaseType._raw( + this.descriptor, + this.typeConstantSuffix, + this.unprefixed, + this.setter, + this.generator, + ); bool get isGroup => descriptor == FieldDescriptorProto_Type.TYPE_GROUP; bool get isMessage => descriptor == FieldDescriptorProto_Type.TYPE_MESSAGE; @@ -38,9 +43,10 @@ class BaseType { String get package => generator == null ? '' : generator!.package; /// The Dart expression to use for this type when in a different file. - String prefixed(FileGenerator fileGen) => generator == null - ? unprefixed - : '${generator!.importPrefix(context: fileGen)}.$unprefixed'; + String prefixed(FileGenerator fileGen) => + generator == null + ? unprefixed + : '${generator!.importPrefix(context: fileGen)}.$unprefixed'; /// Returns the name to use in generated code for this Dart type. /// @@ -64,54 +70,125 @@ class BaseType { switch (field.type) { case FieldDescriptorProto_Type.TYPE_BOOL: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_BOOL, 'B', - '$coreImportPrefix.bool', r'$_setBool', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_BOOL, + 'B', + '$coreImportPrefix.bool', + r'$_setBool', + null, + ); case FieldDescriptorProto_Type.TYPE_FLOAT: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_FLOAT, 'F', - '$coreImportPrefix.double', r'$_setFloat', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_FLOAT, + 'F', + '$coreImportPrefix.double', + r'$_setFloat', + null, + ); case FieldDescriptorProto_Type.TYPE_DOUBLE: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_DOUBLE, 'D', - '$coreImportPrefix.double', r'$_setDouble', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_DOUBLE, + 'D', + '$coreImportPrefix.double', + r'$_setDouble', + null, + ); case FieldDescriptorProto_Type.TYPE_INT32: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_INT32, '3', - '$coreImportPrefix.int', r'$_setSignedInt32', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_INT32, + '3', + '$coreImportPrefix.int', + r'$_setSignedInt32', + null, + ); case FieldDescriptorProto_Type.TYPE_UINT32: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_UINT32, 'U3', - '$coreImportPrefix.int', r'$_setUnsignedInt32', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_UINT32, + 'U3', + '$coreImportPrefix.int', + r'$_setUnsignedInt32', + null, + ); case FieldDescriptorProto_Type.TYPE_SINT32: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_SINT32, 'S3', - '$coreImportPrefix.int', r'$_setSignedInt32', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_SINT32, + 'S3', + '$coreImportPrefix.int', + r'$_setSignedInt32', + null, + ); case FieldDescriptorProto_Type.TYPE_FIXED32: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_FIXED32, 'F3', - '$coreImportPrefix.int', r'$_setUnsignedInt32', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_FIXED32, + 'F3', + '$coreImportPrefix.int', + r'$_setUnsignedInt32', + null, + ); case FieldDescriptorProto_Type.TYPE_SFIXED32: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_SFIXED32, - 'SF3', '$coreImportPrefix.int', r'$_setSignedInt32', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_SFIXED32, + 'SF3', + '$coreImportPrefix.int', + r'$_setSignedInt32', + null, + ); case FieldDescriptorProto_Type.TYPE_INT64: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_INT64, '6', - '$fixnumImportPrefix.Int64', r'$_setInt64', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_INT64, + '6', + '$fixnumImportPrefix.Int64', + r'$_setInt64', + null, + ); case FieldDescriptorProto_Type.TYPE_UINT64: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_UINT64, 'U6', - '$fixnumImportPrefix.Int64', r'$_setInt64', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_UINT64, + 'U6', + '$fixnumImportPrefix.Int64', + r'$_setInt64', + null, + ); case FieldDescriptorProto_Type.TYPE_SINT64: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_SINT64, 'S6', - '$fixnumImportPrefix.Int64', r'$_setInt64', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_SINT64, + 'S6', + '$fixnumImportPrefix.Int64', + r'$_setInt64', + null, + ); case FieldDescriptorProto_Type.TYPE_FIXED64: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_FIXED64, 'F6', - '$fixnumImportPrefix.Int64', r'$_setInt64', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_FIXED64, + 'F6', + '$fixnumImportPrefix.Int64', + r'$_setInt64', + null, + ); case FieldDescriptorProto_Type.TYPE_SFIXED64: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_SFIXED64, - 'SF6', '$fixnumImportPrefix.Int64', r'$_setInt64', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_SFIXED64, + 'SF6', + '$fixnumImportPrefix.Int64', + r'$_setInt64', + null, + ); case FieldDescriptorProto_Type.TYPE_STRING: - return const BaseType._raw(FieldDescriptorProto_Type.TYPE_STRING, 'S', - '$coreImportPrefix.String', r'$_setString', null); + return const BaseType._raw( + FieldDescriptorProto_Type.TYPE_STRING, + 'S', + '$coreImportPrefix.String', + r'$_setString', + null, + ); case FieldDescriptorProto_Type.TYPE_BYTES: return const BaseType._raw( - FieldDescriptorProto_Type.TYPE_BYTES, - 'Y', - '$coreImportPrefix.List<$coreImportPrefix.int>', - r'$_setBytes', - null); + FieldDescriptorProto_Type.TYPE_BYTES, + 'Y', + '$coreImportPrefix.List<$coreImportPrefix.int>', + r'$_setBytes', + null, + ); case FieldDescriptorProto_Type.TYPE_GROUP: constSuffix = 'G'; @@ -133,6 +210,11 @@ class BaseType { } return BaseType._raw( - field.type, constSuffix, generator.classname!, null, generator); + field.type, + constSuffix, + generator.classname!, + null, + generator, + ); } } diff --git a/protoc_plugin/lib/src/client_generator.dart b/protoc_plugin/lib/src/client_generator.dart index 3b4bbfb2c..b18ac2d78 100644 --- a/protoc_plugin/lib/src/client_generator.dart +++ b/protoc_plugin/lib/src/client_generator.dart @@ -22,23 +22,22 @@ class ClientApiGenerator { late final List _serviceDescriptorPath = [ ...service.fileGen.fieldPath, fileDescriptorServiceTag, - _repeatedFieldIndex + _repeatedFieldIndex, ]; List _methodDescriptorPath(int methodIndex) { - return [ - ..._serviceDescriptorPath, - serviceDescriptorMethodTag, - methodIndex, - ]; + return [..._serviceDescriptorPath, serviceDescriptorMethodTag, methodIndex]; } ClientApiGenerator( - this.service, Set usedNames, this._repeatedFieldIndex) - : className = disambiguateName( - avoidInitialUnderscore(service._descriptor.name), - usedNames, - defaultSuffixes()); + this.service, + Set usedNames, + this._repeatedFieldIndex, + ) : className = disambiguateName( + avoidInitialUnderscore(service._descriptor.name), + usedNames, + defaultSuffixes(), + ); // Subclasses can override this. String get _clientType => '$protobufImportPrefix.RpcClient'; @@ -50,7 +49,8 @@ class ClientApiGenerator { } if (service._descriptor.options.deprecated) { out.println( - '@$coreImportPrefix.Deprecated(\'This service is deprecated\')'); + '@$coreImportPrefix.Deprecated(\'This service is deprecated\')', + ); } out.addBlock('class ${className}Api {', '}', () { out.println('final $_clientType _client;'); @@ -67,30 +67,44 @@ class ClientApiGenerator { // Subclasses can override this. void generateMethod( - IndentingWriter out, MethodDescriptorProto method, int methodIndex) { + IndentingWriter out, + MethodDescriptorProto method, + int methodIndex, + ) { final methodName = disambiguateName( - avoidInitialUnderscore(service._methodName(method.name)), - usedMethodNames, - defaultSuffixes()); - final inputType = - service._getDartClassName(method.inputType, forMainFile: true); - final outputType = - service._getDartClassName(method.outputType, forMainFile: true); - final commentBlock = - service.fileGen.commentBlock(_methodDescriptorPath(methodIndex)); + avoidInitialUnderscore(service._methodName(method.name)), + usedMethodNames, + defaultSuffixes(), + ); + final inputType = service._getDartClassName( + method.inputType, + forMainFile: true, + ); + final outputType = service._getDartClassName( + method.outputType, + forMainFile: true, + ); + final commentBlock = service.fileGen.commentBlock( + _methodDescriptorPath(methodIndex), + ); if (commentBlock != null) { out.println(commentBlock); } if (method.options.deprecated) { out.println( - '@$coreImportPrefix.Deprecated(\'This method is deprecated\')'); + '@$coreImportPrefix.Deprecated(\'This method is deprecated\')', + ); } out.addBlock( - '$asyncImportPrefix.Future<$outputType> $methodName(' - '$protobufImportPrefix.ClientContext? ctx, $inputType request) =>', - ';', () { - out.println('_client.invoke<$outputType>(ctx, \'$className\', ' - '\'${method.name}\', request, $outputType())'); - }); + '$asyncImportPrefix.Future<$outputType> $methodName(' + '$protobufImportPrefix.ClientContext? ctx, $inputType request) =>', + ';', + () { + out.println( + '_client.invoke<$outputType>(ctx, \'$className\', ' + '\'${method.name}\', request, $outputType())', + ); + }, + ); } } diff --git a/protoc_plugin/lib/src/code_generator.dart b/protoc_plugin/lib/src/code_generator.dart index 11173a2b8..8d4acad0a 100644 --- a/protoc_plugin/lib/src/code_generator.dart +++ b/protoc_plugin/lib/src/code_generator.dart @@ -131,8 +131,9 @@ class CodeGenerator { response.file.addAll(gen.generateFiles(config)); } } - response.supportedFeatures = - Int64(CodeGeneratorResponse_Feature.FEATURE_PROTO3_OPTIONAL.value); + response.supportedFeatures = Int64( + CodeGeneratorResponse_Feature.FEATURE_PROTO3_OPTIONAL.value, + ); _streamOut.add(response.writeToBuffer()); } } diff --git a/protoc_plugin/lib/src/enum_generator.dart b/protoc_plugin/lib/src/enum_generator.dart index 3c9fc98e6..d7e992a8e 100644 --- a/protoc_plugin/lib/src/enum_generator.dart +++ b/protoc_plugin/lib/src/enum_generator.dart @@ -34,20 +34,29 @@ class EnumGenerator extends ProtobufContainer { @override late final List fieldPath = [...parent.fieldPath, ..._fieldPathSegment]; - EnumGenerator._(EnumDescriptorProto descriptor, this.parent, - Set usedClassNames, int repeatedFieldIndex, int fieldIdTag) - : _fieldPathSegment = [fieldIdTag, repeatedFieldIndex], - classname = messageOrEnumClassName(descriptor.name, usedClassNames, - parent: parent.classname ?? ''), - fullName = parent.fullName == '' - ? descriptor.name - : '${parent.fullName}.${descriptor.name}', - _descriptor = descriptor { + EnumGenerator._( + EnumDescriptorProto descriptor, + this.parent, + Set usedClassNames, + int repeatedFieldIndex, + int fieldIdTag, + ) : _fieldPathSegment = [fieldIdTag, repeatedFieldIndex], + classname = messageOrEnumClassName( + descriptor.name, + usedClassNames, + parent: parent.classname ?? '', + ), + fullName = + parent.fullName == '' + ? descriptor.name + : '${parent.fullName}.${descriptor.name}', + _descriptor = descriptor { final usedNames = {...reservedEnumNames}; for (var i = 0; i < descriptor.value.length; i++) { final value = descriptor.value[i]; - final canonicalValue = - descriptor.value.firstWhere((v) => v.number == value.number); + final canonicalValue = descriptor.value.firstWhere( + (v) => v.number == value.number, + ); if (value == canonicalValue) { _canonicalValues.add(value); _originalCanonicalIndices.add(i); @@ -56,7 +65,10 @@ class EnumGenerator extends ProtobufContainer { _originalAliasIndices.add(i); } dartNames[value.name] = disambiguateName( - avoidInitialUnderscore(value.name), usedNames, enumSuffixes()); + avoidInitialUnderscore(value.name), + usedNames, + enumSuffixes(), + ); } } @@ -64,17 +76,30 @@ class EnumGenerator extends ProtobufContainer { static const _nestedFieldTag = 4; EnumGenerator.topLevel( - EnumDescriptorProto descriptor, - ProtobufContainer parent, - Set usedClassNames, - int repeatedFieldIndex) - : this._(descriptor, parent, usedClassNames, repeatedFieldIndex, - _topLevelFieldTag); - - EnumGenerator.nested(EnumDescriptorProto descriptor, ProtobufContainer parent, - Set usedClassNames, int repeatedFieldIndex) - : this._(descriptor, parent, usedClassNames, repeatedFieldIndex, - _nestedFieldTag); + EnumDescriptorProto descriptor, + ProtobufContainer parent, + Set usedClassNames, + int repeatedFieldIndex, + ) : this._( + descriptor, + parent, + usedClassNames, + repeatedFieldIndex, + _topLevelFieldTag, + ); + + EnumGenerator.nested( + EnumDescriptorProto descriptor, + ProtobufContainer parent, + Set usedClassNames, + int repeatedFieldIndex, + ) : this._( + descriptor, + parent, + usedClassNames, + repeatedFieldIndex, + _nestedFieldTag, + ); @override String get package => parent.package; @@ -110,106 +135,128 @@ class EnumGenerator extends ProtobufContainer { out.println('@$coreImportPrefix.Deprecated(\'This enum is deprecated\')'); } out.addAnnotatedBlock( - 'class $classname extends $protobufImportPrefix.ProtobufEnum {', - '}\n', [ - NamedLocation( - name: classname, fieldPathSegment: fieldPath, start: 'class '.length) - ], () { - // ----------------------------------------------------------------- - // Define enum types. - final omitEnumNames = ConditionalConstDefinition('omit_enum_names'); - for (var i = 0; i < _canonicalValues.length; i++) { - final val = _canonicalValues[i]; - final name = dartNames[val.name]!; - out.addSuffix( - omitEnumNames.constFieldName, omitEnumNames.constDefinition); - final conditionalValName = omitEnumNames.createTernary(val.name); - final fieldPathSegment = List.from(fieldPath) - ..addAll([_enumValueTag, _originalCanonicalIndices[i]]); - - final commentBlock = fileGen?.commentBlock(fieldPathSegment); - if (commentBlock != null) { - out.println(commentBlock); - } - - if (val.options.deprecated) { - out.println( - '@$coreImportPrefix.Deprecated(\'This enum value is deprecated\')'); - } + 'class $classname extends $protobufImportPrefix.ProtobufEnum {', + '}\n', + [ + NamedLocation( + name: classname, + fieldPathSegment: fieldPath, + start: 'class '.length, + ), + ], + () { + // ----------------------------------------------------------------- + // Define enum types. + final omitEnumNames = ConditionalConstDefinition('omit_enum_names'); + for (var i = 0; i < _canonicalValues.length; i++) { + final val = _canonicalValues[i]; + final name = dartNames[val.name]!; + out.addSuffix( + omitEnumNames.constFieldName, + omitEnumNames.constDefinition, + ); + final conditionalValName = omitEnumNames.createTernary(val.name); + final fieldPathSegment = List.from(fieldPath) + ..addAll([_enumValueTag, _originalCanonicalIndices[i]]); + + final commentBlock = fileGen?.commentBlock(fieldPathSegment); + if (commentBlock != null) { + out.println(commentBlock); + } + + if (val.options.deprecated) { + out.println( + '@$coreImportPrefix.Deprecated(\'This enum value is deprecated\')', + ); + } - out.printlnAnnotated( + out.printlnAnnotated( 'static const $classname $name = ' '$classname._(${val.number}, $conditionalValName);', [ NamedLocation( - name: name, - fieldPathSegment: fieldPathSegment, - start: 'static const $classname '.length) - ]); - } - if (_aliases.isNotEmpty) { - out.println(); - for (var i = 0; i < _aliases.length; i++) { - final alias = _aliases[i]; - final name = dartNames[alias.value.name]!; - out.printlnAnnotated( + name: name, + fieldPathSegment: fieldPathSegment, + start: 'static const $classname '.length, + ), + ], + ); + } + if (_aliases.isNotEmpty) { + out.println(); + for (var i = 0; i < _aliases.length; i++) { + final alias = _aliases[i]; + final name = dartNames[alias.value.name]!; + out.printlnAnnotated( 'static const $classname $name =' ' ${dartNames[alias.canonicalValue.name]};', [ NamedLocation( - name: name, - fieldPathSegment: List.from(fieldPath) - ..addAll([_enumValueTag, _originalAliasIndices[i]]), - start: 'static const $classname '.length) - ]); + name: name, + fieldPathSegment: List.from(fieldPath) + ..addAll([_enumValueTag, _originalAliasIndices[i]]), + start: 'static const $classname '.length, + ), + ], + ); + } } - } - out.println(); + out.println(); - out.println('static const $coreImportPrefix.List<$classname> values =' - ' <$classname> ['); - for (final val in _canonicalValues) { - final name = dartNames[val.name]; - out.println(' $name,'); - } - out.println('];'); - out.println(); - - var maxEnumValue = -1; - for (final valueDescriptor in _canonicalValues) { - if (valueDescriptor.number.isNegative) { - maxEnumValue = -1; // don't use list - break; + out.println( + 'static const $coreImportPrefix.List<$classname> values =' + ' <$classname> [', + ); + for (final val in _canonicalValues) { + final name = dartNames[val.name]; + out.println(' $name,'); } - if (valueDescriptor.number > maxEnumValue) { - maxEnumValue = valueDescriptor.number; + out.println('];'); + out.println(); + + var maxEnumValue = -1; + for (final valueDescriptor in _canonicalValues) { + if (valueDescriptor.number.isNegative) { + maxEnumValue = -1; // don't use list + break; + } + if (valueDescriptor.number > maxEnumValue) { + maxEnumValue = valueDescriptor.number; + } } - } - final useList = _canonicalValues.isEmpty || - (maxEnumValue >= 0 && - _canonicalValues.length / (maxEnumValue + 1) >= 0.7); + final useList = + _canonicalValues.isEmpty || + (maxEnumValue >= 0 && + _canonicalValues.length / (maxEnumValue + 1) >= 0.7); - if (useList) { - out.println( + if (useList) { + out.println( 'static final $coreImportPrefix.List<$classname?> _byValue =' - ' $protobufImportPrefix.ProtobufEnum.\$_initByValueList(values, $maxEnumValue);'); + ' $protobufImportPrefix.ProtobufEnum.\$_initByValueList(values, $maxEnumValue);', + ); - out.println('static $classname? valueOf($coreImportPrefix.int value) =>' - ' value < 0 || value >= _byValue.length ? null : _byValue[value];'); - } else { - out.println( + out.println( + 'static $classname? valueOf($coreImportPrefix.int value) =>' + ' value < 0 || value >= _byValue.length ? null : _byValue[value];', + ); + } else { + out.println( 'static final $coreImportPrefix.Map<$coreImportPrefix.int, $classname> _byValue =' - ' $protobufImportPrefix.ProtobufEnum.initByValue(values);'); + ' $protobufImportPrefix.ProtobufEnum.initByValue(values);', + ); - out.println('static $classname? valueOf($coreImportPrefix.int value) =>' - ' _byValue[value];'); - } + out.println( + 'static $classname? valueOf($coreImportPrefix.int value) =>' + ' _byValue[value];', + ); + } - out.println(); + out.println(); - out.println('const $classname._(super.value, super.name);'); - }); + out.println('const $classname._(super.value, super.name);'); + }, + ); } /// Writes a Dart constant containing the JSON for the EnumProtoDescriptor. @@ -217,8 +264,10 @@ class EnumGenerator extends ProtobufContainer { final name = getJsonConstant(fileGen!); final json = _descriptor.writeToJsonMap(); - out.println('@$coreImportPrefix.Deprecated' - '(\'Use ${toplevelParent!.binaryDescriptorName} instead\')'); + out.println( + '@$coreImportPrefix.Deprecated' + '(\'Use ${toplevelParent!.binaryDescriptorName} instead\')', + ); out.print('const $name = '); writeJsonConst(out, json); out.println(';'); diff --git a/protoc_plugin/lib/src/extension_generator.dart b/protoc_plugin/lib/src/extension_generator.dart index 03ace9826..229d10527 100644 --- a/protoc_plugin/lib/src/extension_generator.dart +++ b/protoc_plugin/lib/src/extension_generator.dart @@ -18,22 +18,42 @@ class ExtensionGenerator { /// See [ProtobufContainer] late final List fieldPath = [..._parent.fieldPath, ..._fieldPathSegment]; - ExtensionGenerator._(this._descriptor, this._parent, Set usedNames, - int repeatedFieldIndex, int fieldIdTag) - : _extensionName = extensionName(_descriptor, usedNames), - _fieldPathSegment = [fieldIdTag, repeatedFieldIndex]; + ExtensionGenerator._( + this._descriptor, + this._parent, + Set usedNames, + int repeatedFieldIndex, + int fieldIdTag, + ) : _extensionName = extensionName(_descriptor, usedNames), + _fieldPathSegment = [fieldIdTag, repeatedFieldIndex]; static const _topLevelFieldTag = 7; static const _nestedFieldTag = 6; - ExtensionGenerator.topLevel(FieldDescriptorProto descriptor, - ProtobufContainer parent, Set usedNames, int repeatedFieldIndex) - : this._(descriptor, parent, usedNames, repeatedFieldIndex, - _topLevelFieldTag); - ExtensionGenerator.nested(FieldDescriptorProto descriptor, - ProtobufContainer parent, Set usedNames, int repeatedFieldIndex) - : this._( - descriptor, parent, usedNames, repeatedFieldIndex, _nestedFieldTag); + ExtensionGenerator.topLevel( + FieldDescriptorProto descriptor, + ProtobufContainer parent, + Set usedNames, + int repeatedFieldIndex, + ) : this._( + descriptor, + parent, + usedNames, + repeatedFieldIndex, + _topLevelFieldTag, + ); + ExtensionGenerator.nested( + FieldDescriptorProto descriptor, + ProtobufContainer parent, + Set usedNames, + int repeatedFieldIndex, + ) : this._( + descriptor, + parent, + usedNames, + repeatedFieldIndex, + _nestedFieldTag, + ); void resolve(GenerationContext ctx) { _field = ProtobufField.extension(_descriptor, _parent, ctx); @@ -67,7 +87,9 @@ class ExtensionGenerator { /// For each .pb.dart file that the generated code needs to import, /// add its generator. void addImportsTo( - Set imports, Set enumImports) { + Set imports, + Set enumImports, + ) { if (!_resolved) throw StateError('resolve not called'); final typeGen = _field.baseType.generator; if (typeGen is EnumGenerator) { @@ -94,13 +116,18 @@ class ExtensionGenerator { final omitFieldNames = ConditionalConstDefinition('omit_field_names'); out.addSuffix( - omitFieldNames.constFieldName, omitFieldNames.constDefinition); + omitFieldNames.constFieldName, + omitFieldNames.constDefinition, + ); final conditionalName = omitFieldNames.createTernary(_extensionName); final omitMessageNames = ConditionalConstDefinition('omit_message_names'); out.addSuffix( - omitMessageNames.constFieldName, omitMessageNames.constDefinition); - final conditionalExtendedName = - omitMessageNames.createTernary(_extendedFullName); + omitMessageNames.constFieldName, + omitMessageNames.constDefinition, + ); + final conditionalExtendedName = omitMessageNames.createTernary( + _extendedFullName, + ); String invocation; final positionals = []; @@ -134,13 +161,15 @@ class ExtensionGenerator { } final fieldDefinition = 'static final '; out.printAnnotated( - '$fieldDefinition$name = ' - '$invocation(${ProtobufField._formatArguments(positionals, named)});\n', - [ - NamedLocation( - name: name, - fieldPathSegment: List.from(fieldPath), - start: fieldDefinition.length) - ]); + '$fieldDefinition$name = ' + '$invocation(${ProtobufField._formatArguments(positionals, named)});\n', + [ + NamedLocation( + name: name, + fieldPathSegment: List.from(fieldPath), + start: fieldDefinition.length, + ), + ], + ); } } diff --git a/protoc_plugin/lib/src/file_generator.dart b/protoc_plugin/lib/src/file_generator.dart index f9b99de63..807fd4ed1 100644 --- a/protoc_plugin/lib/src/file_generator.dart +++ b/protoc_plugin/lib/src/file_generator.dart @@ -18,10 +18,7 @@ const String _protobufImportUrl = 'package:protobuf/protobuf.dart'; const String _typedDataImportPrefix = r'$typed_data'; const String _typedDataImportUrl = 'dart:typed_data'; -enum ProtoSyntax { - proto2, - proto3, -} +enum ProtoSyntax { proto2, proto3 } /// Generates the Dart output files for one .proto input file. /// @@ -50,11 +47,14 @@ class FileGenerator extends ProtobufContainer { } if (!mixin.name.startsWith(_dartIdentifier)) { throw mixinError( - '"${mixin.name}" is not a valid dart class identifier'); + '"${mixin.name}" is not a valid dart class identifier', + ); } if (mixin.hasParent() && !mixin.parent.startsWith(_dartIdentifier)) { - throw mixinError('Mixin parent "${mixin.parent}" of "${mixin.name}" is ' - 'not a valid dart class identifier'); + throw mixinError( + 'Mixin parent "${mixin.parent}" of "${mixin.name}" is ' + 'not a valid dart class identifier', + ); } dartMixins[mixin.name] = mixin; } @@ -73,8 +73,10 @@ class FileGenerator extends ProtobufContainer { if (internalMixin) break; // No further validation of parent chain. if (!declaredMixin) { - throw mixinError('Unknown mixin parent "${mixin.parent}" of ' - '"${currentMixin.name}"'); + throw mixinError( + 'Unknown mixin parent "${mixin.parent}" of ' + '"${currentMixin.name}"', + ); } if (parentChain.contains(parentName)) { @@ -92,9 +94,11 @@ class FileGenerator extends ProtobufContainer { if (pbMixins.containsKey(name)) return pbMixins[name]; if (dartMixins.containsKey(name)) { final dartMixin = dartMixins[name]!; - final pbMixin = PbMixin(dartMixin.name, - importFrom: dartMixin.importFrom, - parent: resolveMixin(dartMixin.parent)); + final pbMixin = PbMixin( + dartMixin.name, + importFrom: dartMixin.importFrom, + parent: resolveMixin(dartMixin.parent), + ); pbMixins[name] = pbMixin; return pbMixin; } @@ -122,16 +126,16 @@ class FileGenerator extends ProtobufContainer { /// Used to avoid collisions after names have been mangled to match the Dart /// style. - final Set usedTopLevelNames = {} - ..addAll(forbiddenTopLevelNames); + final Set usedTopLevelNames = + {}..addAll(forbiddenTopLevelNames); /// Used to avoid collisions in the service file after names have been mangled /// to match the dart style. - final Set usedTopLevelServiceNames = {} - ..addAll(forbiddenTopLevelNames); + final Set usedTopLevelServiceNames = + {}..addAll(forbiddenTopLevelNames); - final Set usedExtensionNames = {} - ..addAll(forbiddenExtensionNames); + final Set usedExtensionNames = + {}..addAll(forbiddenExtensionNames); /// Whether cross-references have been resolved. bool _linked = false; @@ -139,10 +143,11 @@ class FileGenerator extends ProtobufContainer { final ProtoSyntax syntax; FileGenerator(this.descriptor, this.options) - : protoFileUri = Uri.file(descriptor.name), - syntax = descriptor.syntax == 'proto3' - ? ProtoSyntax.proto3 - : ProtoSyntax.proto2 { + : protoFileUri = Uri.file(descriptor.name), + syntax = + descriptor.syntax == 'proto3' + ? ProtoSyntax.proto3 + : ProtoSyntax.proto2 { if (protoFileUri.isAbsolute) { // protoc should never generate an import with an absolute path. throw 'FAILURE: Import with absolute path is not supported'; @@ -151,7 +156,7 @@ class FileGenerator extends ProtobufContainer { final declaredMixins = _getDeclaredMixins(descriptor); final defaultMixinName = descriptor.options.getExtension(Dart_options.defaultMixin) as String? ?? - ''; + ''; final defaultMixin = declaredMixins[defaultMixinName] ?? findMixin(defaultMixinName); if (defaultMixin == null && defaultMixinName.isNotEmpty) { @@ -161,27 +166,51 @@ class FileGenerator extends ProtobufContainer { // Load and register all enum and message types. for (var i = 0; i < descriptor.enumType.length; i++) { - enumGenerators.add(EnumGenerator.topLevel( - descriptor.enumType[i], this, usedTopLevelNames, i)); + enumGenerators.add( + EnumGenerator.topLevel( + descriptor.enumType[i], + this, + usedTopLevelNames, + i, + ), + ); } for (var i = 0; i < descriptor.messageType.length; i++) { - messageGenerators.add(MessageGenerator.topLevel(descriptor.messageType[i], - this, declaredMixins, defaultMixin, usedTopLevelNames, i)); + messageGenerators.add( + MessageGenerator.topLevel( + descriptor.messageType[i], + this, + declaredMixins, + defaultMixin, + usedTopLevelNames, + i, + ), + ); } for (var i = 0; i < descriptor.extension.length; i++) { - extensionGenerators.add(ExtensionGenerator.topLevel( - descriptor.extension[i], this, usedExtensionNames, i)); + extensionGenerators.add( + ExtensionGenerator.topLevel( + descriptor.extension[i], + this, + usedExtensionNames, + i, + ), + ); } for (var i = 0; i < descriptor.service.length; i++) { final service = descriptor.service[i]; if (options.useGrpc) { grpcGenerators.add(GrpcServiceGenerator(service, this, i)); } else { - final serviceGen = - ServiceGenerator(service, this, usedTopLevelServiceNames); + final serviceGen = ServiceGenerator( + service, + this, + usedTopLevelServiceNames, + ); serviceGenerators.add(serviceGen); - clientApiGenerators - .add(ClientApiGenerator(serviceGen, usedTopLevelNames, i)); + clientApiGenerators.add( + ClientApiGenerator(serviceGen, usedTopLevelNames, i), + ); } } } @@ -243,10 +272,14 @@ class FileGenerator extends ProtobufContainer { if (options.generateMetadata) { files.addAll([ - makeFile('.pb.dart.meta', - mainWriter.sourceLocationInfo.writeToJson().toString()), - makeFile('.pbenum.dart.meta', - enumWriter.sourceLocationInfo.writeToJson().toString()) + makeFile( + '.pb.dart.meta', + mainWriter.sourceLocationInfo.writeToJson().toString(), + ), + makeFile( + '.pbenum.dart.meta', + enumWriter.sourceLocationInfo.writeToJson().toString(), + ), ]); } if (options.useGrpc) { @@ -263,11 +296,13 @@ class FileGenerator extends ProtobufContainer { /// Creates an IndentingWriter with metadata generation enabled or disabled. IndentingWriter makeWriter() => IndentingWriter( - filename: options.generateMetadata ? descriptor.name : null); + filename: options.generateMetadata ? descriptor.name : null, + ); /// Returns the contents of the .pb.dart file for this .proto file. - IndentingWriter generateMainFile( - [OutputConfiguration config = const DefaultOutputConfiguration()]) { + IndentingWriter generateMainFile([ + OutputConfiguration config = const DefaultOutputConfiguration(), + ]) { if (!_linked) throw StateError('not linked'); final out = makeWriter(); @@ -287,8 +322,10 @@ class FileGenerator extends ProtobufContainer { for (final x in extensionGenerators) { x.generate(out); } - out.println('static void registerAllExtensions(' - '$protobufImportPrefix.ExtensionRegistry registry) {'); + out.println( + 'static void registerAllExtensions(' + '$protobufImportPrefix.ExtensionRegistry registry) {', + ); for (final x in extensionGenerators) { out.println(' registry.add(${x.name});'); } @@ -303,8 +340,10 @@ class FileGenerator extends ProtobufContainer { } /// Writes the header and imports for the .pb.dart file. - void writeMainHeader(IndentingWriter out, - [OutputConfiguration config = const DefaultOutputConfiguration()]) { + void writeMainHeader( + IndentingWriter out, [ + OutputConfiguration config = const DefaultOutputConfiguration(), + ]) { final importWriter = ImportWriter(); // We only add the dart:async import if there are generic client API @@ -316,8 +355,10 @@ class FileGenerator extends ProtobufContainer { importWriter.addImport(_coreImportUrl, prefix: coreImportPrefix); if (_needsFixnumImport) { - importWriter.addImport('package:fixnum/fixnum.dart', - prefix: fixnumImportPrefix); + importWriter.addImport( + 'package:fixnum/fixnum.dart', + prefix: fixnumImportPrefix, + ); } if (_needsProtobufImport) { @@ -345,18 +386,27 @@ class FileGenerator extends ProtobufContainer { } } - importWriter.addExport(_protobufImportUrl, - members: ['GeneratedMessageGenericExtensions']); + importWriter.addExport( + _protobufImportUrl, + members: ['GeneratedMessageGenericExtensions'], + ); for (final publicDependency in descriptor.publicDependency) { - _addExport(importWriter, config, - Uri.file(descriptor.dependency[publicDependency]), '.pb.dart'); + _addExport( + importWriter, + config, + Uri.file(descriptor.dependency[publicDependency]), + '.pb.dart', + ); } // Export enums in main file for backward compatibility. if (hasEnums) { - final url = - config.resolveImport(protoFileUri, protoFileUri, '.pbenum.dart'); + final url = config.resolveImport( + protoFileUri, + protoFileUri, + '.pbenum.dart', + ); importWriter.addExport(url.toString()); } @@ -364,9 +414,10 @@ class FileGenerator extends ProtobufContainer { // should likely refactor this so they're regular (non-src/) references. // // For now, we surpress the analysis warning. - _writeHeading(out, extraIgnores: { - if (importWriter.hasSrcImport) 'implementation_imports', - }); + _writeHeading( + out, + extraIgnores: {if (importWriter.hasSrcImport) 'implementation_imports'}, + ); out.println(importWriter.emit()); } @@ -388,7 +439,9 @@ class FileGenerator extends ProtobufContainer { /// Returns the generator for each .pb.dart file we need to import. void _findProtosToImport( - Set imports, Set enumImports) { + Set imports, + Set enumImports, + ) { for (final m in messageGenerators) { m.addImportsTo(imports, enumImports); } @@ -411,15 +464,15 @@ class FileGenerator extends ProtobufContainer { } return mixins - .map((mixin) => mixin.importFrom) - .toSet() - .toList(growable: false) - ..sort(); + .map((mixin) => mixin.importFrom) + .toSet() + .toList(growable: false)..sort(); } /// Returns the contents of the .pbenum.dart file for this .proto file. - IndentingWriter generateEnumFile( - [OutputConfiguration config = const DefaultOutputConfiguration()]) { + IndentingWriter generateEnumFile([ + OutputConfiguration config = const DefaultOutputConfiguration(), + ]) { if (!_linked) throw StateError('not linked'); final out = makeWriter(); @@ -435,8 +488,12 @@ class FileGenerator extends ProtobufContainer { } for (final publicDependency in descriptor.publicDependency) { - _addExport(importWriter, config, - Uri.file(descriptor.dependency[publicDependency]), '.pbenum.dart'); + _addExport( + importWriter, + config, + Uri.file(descriptor.dependency[publicDependency]), + '.pbenum.dart', + ); } if (importWriter.hasImports) { @@ -468,13 +525,16 @@ class FileGenerator extends ProtobufContainer { bool get hasEnums => enumCount > 0; /// Returns the contents of the .pbserver.dart file for this .proto file. - String generateServerFile( - [OutputConfiguration config = const DefaultOutputConfiguration()]) { + String generateServerFile([ + OutputConfiguration config = const DefaultOutputConfiguration(), + ]) { if (!_linked) throw StateError('not linked'); final out = makeWriter(); - _writeHeading(out, - extraIgnores: {'deprecated_member_use_from_same_package'}); + _writeHeading( + out, + extraIgnores: {'deprecated_member_use_from_same_package'}, + ); final importWriter = ImportWriter(); @@ -513,8 +573,9 @@ class FileGenerator extends ProtobufContainer { } /// Returns the contents of the .pbgrpc.dart file for this .proto file. - String generateGrpcFile( - [OutputConfiguration config = const DefaultOutputConfiguration()]) { + String generateGrpcFile([ + OutputConfiguration config = const DefaultOutputConfiguration(), + ]) { if (!_linked) throw StateError('not linked'); final out = makeWriter(); @@ -548,19 +609,29 @@ class FileGenerator extends ProtobufContainer { return out.toString(); } - void writeBinaryDescriptor(IndentingWriter out, String identifierName, - String name, GeneratedMessage descriptor) { + void writeBinaryDescriptor( + IndentingWriter out, + String identifierName, + String name, + GeneratedMessage descriptor, + ) { final base64 = base64Encode(descriptor.writeToBuffer()); - out.println('/// Descriptor for `$name`. Decode as a ' - '`${descriptor.info_.qualifiedMessageName}`.'); + out.println( + '/// Descriptor for `$name`. Decode as a ' + '`${descriptor.info_.qualifiedMessageName}`.', + ); const indent = ' '; - final base64Lines = - _splitString(base64, 74).map((s) => "'$s'").join('\n$indent'); - out.println('final $_typedDataImportPrefix.Uint8List ' - '$identifierName = ' - '$_convertImportPrefix.base64Decode(\n$indent$base64Lines);'); + final base64Lines = _splitString( + base64, + 74, + ).map((s) => "'$s'").join('\n$indent'); + out.println( + 'final $_typedDataImportPrefix.Uint8List ' + '$identifierName = ' + '$_convertImportPrefix.base64Decode(\n$indent$base64Lines);', + ); } /// Return the given [str], split into separate segments, where no segment is @@ -576,8 +647,9 @@ class FileGenerator extends ProtobufContainer { } /// Returns the contents of the .pbjson.dart file for this .proto file. - String generateJsonFile( - [OutputConfiguration config = const DefaultOutputConfiguration()]) { + String generateJsonFile([ + OutputConfiguration config = const DefaultOutputConfiguration(), + ]) { if (!_linked) throw StateError('not linked'); final out = makeWriter(); @@ -599,19 +671,31 @@ class FileGenerator extends ProtobufContainer { for (final e in enumGenerators) { e.generateConstants(out); writeBinaryDescriptor( - out, e.binaryDescriptorName, e._descriptor.name, e._descriptor); + out, + e.binaryDescriptorName, + e._descriptor.name, + e._descriptor, + ); out.println(''); } for (final m in messageGenerators) { m.generateConstants(out); writeBinaryDescriptor( - out, m.binaryDescriptorName, m._descriptor.name, m._descriptor); + out, + m.binaryDescriptorName, + m._descriptor.name, + m._descriptor, + ); out.println(''); } for (final s in serviceGenerators) { s.generateConstants(out); writeBinaryDescriptor( - out, s.binaryDescriptorName, s._descriptor.name, s._descriptor); + out, + s.binaryDescriptorName, + s._descriptor.name, + s._descriptor, + ); out.println(''); } @@ -670,8 +754,12 @@ class FileGenerator extends ProtobufContainer { /// Writes an import of a .dart file corresponding to a .proto file. /// (Possibly the same .proto file.) - void _addImport(ImportWriter importWriter, OutputConfiguration config, - FileGenerator target, String ext) { + void _addImport( + ImportWriter importWriter, + OutputConfiguration config, + FileGenerator target, + String ext, + ) { final url = config.resolveImport(target.protoFileUri, protoFileUri, ext); final import = url.toString(); @@ -679,8 +767,10 @@ class FileGenerator extends ProtobufContainer { // evaluate to true not just for the main .pb.dart file based off the proto // file, but also for the .pbserver.dart, .pbgrpc.dart files. if (ext == '.pb.dart' || protoFileUri != target.protoFileUri) { - importWriter.addImport(import, - prefix: target.importPrefix(context: fileGen)); + importWriter.addImport( + import, + prefix: target.importPrefix(context: fileGen), + ); } else { importWriter.addImport(import); } @@ -688,8 +778,12 @@ class FileGenerator extends ProtobufContainer { /// Writes an export of a pb.dart file corresponding to a .proto file. /// (Possibly the same .proto file.) - void _addExport(ImportWriter importWriter, OutputConfiguration config, - Uri target, String ext) { + void _addExport( + ImportWriter importWriter, + OutputConfiguration config, + Uri target, + String ext, + ) { final url = config.resolveImport(target, protoFileUri, ext); importWriter.addExport(url.toString()); } @@ -700,7 +794,7 @@ class ConditionalConstDefinition { final String constFieldName; ConditionalConstDefinition(this.envName) - : constFieldName = _convertToCamelCase(envName); + : constFieldName = _convertToCamelCase(envName); String get constDefinition { return 'const $coreImportPrefix.bool $constFieldName = ' @@ -714,9 +808,10 @@ class ConditionalConstDefinition { // Convert foo_bar_baz to _fooBarBaz. static String _convertToCamelCase(String lowerUnderscoreCase) { final parts = lowerUnderscoreCase.split('_'); - final rest = parts.skip(1).map((item) { - return item.substring(0, 1).toUpperCase() + item.substring(1); - }).join(); + final rest = + parts.skip(1).map((item) { + return item.substring(0, 1).toUpperCase() + item.substring(1); + }).join(); return '_${parts.first}$rest'; } } diff --git a/protoc_plugin/lib/src/grpc_generator.dart b/protoc_plugin/lib/src/grpc_generator.dart index a36d4242c..37852c2d0 100644 --- a/protoc_plugin/lib/src/grpc_generator.dart +++ b/protoc_plugin/lib/src/grpc_generator.dart @@ -121,7 +121,8 @@ class GrpcServiceGenerator { } if (_descriptor.options.deprecated) { out.println( - "@$coreImportPrefix.Deprecated('This service is deprecated')"); + "@$coreImportPrefix.Deprecated('This service is deprecated')", + ); } out.println("@$protobufImportPrefix.GrpcServiceName('$_fullServiceName')"); out.addBlock('class $_clientClassname extends $_client {', '}', () { @@ -147,7 +148,8 @@ class GrpcServiceGenerator { // generate the constructor out.println( - '$_clientClassname(super.channel, {super.options, super.interceptors});'); + '$_clientClassname(super.channel, {super.options, super.interceptors});', + ); // generate the service call methods for (var i = 0; i < _methods.length; i++) { @@ -169,26 +171,30 @@ class GrpcServiceGenerator { void _generateService(IndentingWriter out) { out.println("@$protobufImportPrefix.GrpcServiceName('$_fullServiceName')"); - out.addBlock('abstract class $_serviceClassname extends $_service {', '}', - () { - out.println( - "$coreImportPrefix.String get \$name => '$_fullServiceName';"); - out.println(); - out.addBlock('$_serviceClassname() {', '}', () { + out.addBlock( + 'abstract class $_serviceClassname extends $_service {', + '}', + () { + out.println( + "$coreImportPrefix.String get \$name => '$_fullServiceName';", + ); + out.println(); + out.addBlock('$_serviceClassname() {', '}', () { + for (final method in _methods) { + method.generateServiceMethodRegistration(out); + } + }); + out.println(); for (final method in _methods) { - method.generateServiceMethodRegistration(out); - } - }); - out.println(); - for (final method in _methods) { - if (!method._clientStreaming) { - method.generateServiceMethodPreamble(out); + if (!method._clientStreaming) { + method.generateServiceMethodPreamble(out); + out.println(); + } + method.generateServiceMethodStub(out); out.println(); } - method.generateServiceMethodStub(out); - out.println(); - } - }); + }, + ); } static final String _callOptions = '$grpcImportPrefix.CallOptions'; @@ -216,20 +222,24 @@ class _GrpcMethod { final bool _deprecated; _GrpcMethod._( - this._grpcName, - this._dartName, - this._serviceName, - this._clientStreaming, - this._serverStreaming, - this._requestType, - this._responseType, - this._argumentType, - this._clientReturnType, - this._serverReturnType, - this._deprecated); - - factory _GrpcMethod(GrpcServiceGenerator service, GenerationContext ctx, - MethodDescriptorProto method) { + this._grpcName, + this._dartName, + this._serviceName, + this._clientStreaming, + this._serverStreaming, + this._requestType, + this._responseType, + this._argumentType, + this._clientReturnType, + this._serverReturnType, + this._deprecated, + ); + + factory _GrpcMethod( + GrpcServiceGenerator service, + GenerationContext ctx, + MethodDescriptorProto method, + ) { final grpcName = method.name; final dartName = lowerCaseFirstLetter(grpcName); @@ -244,31 +254,34 @@ class _GrpcMethod { final argumentType = clientStreaming ? '$_stream<$requestType>' : requestType; - final clientReturnType = serverStreaming - ? '$_responseStream<$responseType>' - : '$_responseFuture<$responseType>'; + final clientReturnType = + serverStreaming + ? '$_responseStream<$responseType>' + : '$_responseFuture<$responseType>'; final serverReturnType = serverStreaming ? '$_stream<$responseType>' : '$_future<$responseType>'; final deprecated = method.options.deprecated; return _GrpcMethod._( - grpcName, - dartName, - service._fullServiceName, - clientStreaming, - serverStreaming, - requestType, - responseType, - argumentType, - clientReturnType, - serverReturnType, - deprecated); + grpcName, + dartName, + service._fullServiceName, + clientStreaming, + serverStreaming, + requestType, + responseType, + argumentType, + clientReturnType, + serverReturnType, + deprecated, + ); } void generateClientMethodDescriptor(IndentingWriter out) { out.println( - 'static final _\$$_dartName = $_clientMethod<$_requestType, $_responseType>('); + 'static final _\$$_dartName = $_clientMethod<$_requestType, $_responseType>(', + ); out.println(' \'/$_serviceName/$_grpcName\','); out.println(' ($_requestType value) => value.writeToBuffer(),'); out.println(' $_responseType.fromBuffer);'); @@ -282,35 +295,46 @@ class _GrpcMethod { ]; } - void generateClientStub(IndentingWriter out, - GrpcServiceGenerator serviceGenerator, int methodIndex) { + void generateClientStub( + IndentingWriter out, + GrpcServiceGenerator serviceGenerator, + int methodIndex, + ) { out.println(); - final commentBlock = serviceGenerator.fileGen - .commentBlock(_methodDescriptorPath(serviceGenerator, methodIndex)); + final commentBlock = serviceGenerator.fileGen.commentBlock( + _methodDescriptorPath(serviceGenerator, methodIndex), + ); if (commentBlock != null) { out.println(commentBlock); } if (_deprecated) { out.println( - '@$coreImportPrefix.Deprecated(\'This method is deprecated\')'); + '@$coreImportPrefix.Deprecated(\'This method is deprecated\')', + ); } out.addBlock( - '$_clientReturnType $_dartName($_argumentType request, {${GrpcServiceGenerator._callOptions}? options,}) {', - '}', () { - if (_clientStreaming && _serverStreaming) { - out.println( - 'return \$createStreamingCall(_\$$_dartName, request, options: options);'); - } else if (_clientStreaming && !_serverStreaming) { - out.println( - 'return \$createStreamingCall(_\$$_dartName, request, options: options).single;'); - } else if (!_clientStreaming && _serverStreaming) { - out.println( - 'return \$createStreamingCall(_\$$_dartName, $_stream.fromIterable([request]), options: options);'); - } else { - out.println( - 'return \$createUnaryCall(_\$$_dartName, request, options: options);'); - } - }); + '$_clientReturnType $_dartName($_argumentType request, {${GrpcServiceGenerator._callOptions}? options,}) {', + '}', + () { + if (_clientStreaming && _serverStreaming) { + out.println( + 'return \$createStreamingCall(_\$$_dartName, request, options: options);', + ); + } else if (_clientStreaming && !_serverStreaming) { + out.println( + 'return \$createStreamingCall(_\$$_dartName, request, options: options).single;', + ); + } else if (!_clientStreaming && _serverStreaming) { + out.println( + 'return \$createStreamingCall(_\$$_dartName, $_stream.fromIterable([request]), options: options);', + ); + } else { + out.println( + 'return \$createUnaryCall(_\$$_dartName, request, options: options);', + ); + } + }, + ); } void generateServiceMethodRegistration(IndentingWriter out) { @@ -320,25 +344,29 @@ class _GrpcMethod { out.println(' $_clientStreaming,'); out.println(' $_serverStreaming,'); out.println( - ' ($coreImportPrefix.List<$coreImportPrefix.int> value) => $_requestType.fromBuffer(value),'); + ' ($coreImportPrefix.List<$coreImportPrefix.int> value) => $_requestType.fromBuffer(value),', + ); out.println(' ($_responseType value) => value.writeToBuffer()));'); } void generateServiceMethodPreamble(IndentingWriter out) { out.addBlock( - '$_serverReturnType ${_dartName}_Pre($_serviceCall \$call, $_future<$_requestType> \$request) async${_serverStreaming ? '*' : ''} {', - '}', () { - if (_serverStreaming) { - out.println('yield* $_dartName(\$call, await \$request);'); - } else { - out.println('return $_dartName(\$call, await \$request);'); - } - }); + '$_serverReturnType ${_dartName}_Pre($_serviceCall \$call, $_future<$_requestType> \$request) async${_serverStreaming ? '*' : ''} {', + '}', + () { + if (_serverStreaming) { + out.println('yield* $_dartName(\$call, await \$request);'); + } else { + out.println('return $_dartName(\$call, await \$request);'); + } + }, + ); } void generateServiceMethodStub(IndentingWriter out) { out.println( - '$_serverReturnType $_dartName($_serviceCall call, $_argumentType request);'); + '$_serverReturnType $_dartName($_serviceCall call, $_argumentType request);', + ); } static final String _serviceCall = '$grpcImportPrefix.ServiceCall'; diff --git a/protoc_plugin/lib/src/message_generator.dart b/protoc_plugin/lib/src/message_generator.dart index e31170a8f..f301ea2ff 100644 --- a/protoc_plugin/lib/src/message_generator.dart +++ b/protoc_plugin/lib/src/message_generator.dart @@ -10,7 +10,10 @@ part of '../protoc.dart'; /// corresponding which-method. class OneofEnumGenerator { static void generate( - IndentingWriter out, String classname, List fields) { + IndentingWriter out, + String classname, + List fields, + ) { out.addBlock('enum $classname {', '}\n', () { for (final field in fields) { final name = oneofEnumMemberName(field.memberNames!.fieldName); @@ -77,23 +80,29 @@ class MessageGenerator extends ProtobufContainer { Set _usedTopLevelNames; MessageGenerator._( - DescriptorProto descriptor, - this.parent, - Map declaredMixins, - PbMixin? defaultMixin, - this._usedTopLevelNames, - int repeatedFieldIndex, - int fieldIdTag) - : _descriptor = descriptor, - _fieldPathSegment = [fieldIdTag, repeatedFieldIndex], - classname = messageOrEnumClassName(descriptor.name, _usedTopLevelNames, - parent: parent?.classname ?? ''), - assert(parent != null), - fullName = parent!.fullName == '' - ? descriptor.name - : '${parent.fullName}.${descriptor.name}', - _oneofFields = - List.generate(countRealOneofs(descriptor), (int index) => []) { + DescriptorProto descriptor, + this.parent, + Map declaredMixins, + PbMixin? defaultMixin, + this._usedTopLevelNames, + int repeatedFieldIndex, + int fieldIdTag, + ) : _descriptor = descriptor, + _fieldPathSegment = [fieldIdTag, repeatedFieldIndex], + classname = messageOrEnumClassName( + descriptor.name, + _usedTopLevelNames, + parent: parent?.classname ?? '', + ), + assert(parent != null), + fullName = + parent!.fullName == '' + ? descriptor.name + : '${parent.fullName}.${descriptor.name}', + _oneofFields = List.generate( + countRealOneofs(descriptor), + (int index) => [], + ) { mixin = _getMixin(declaredMixins, defaultMixin); for (var i = 0; i < _descriptor.enumType.length; i++) { final e = _descriptor.enumType[i]; @@ -102,8 +111,16 @@ class MessageGenerator extends ProtobufContainer { for (var i = 0; i < _descriptor.nestedType.length; i++) { final n = _descriptor.nestedType[i]; - _messageGenerators.add(MessageGenerator.nested( - n, this, declaredMixins, defaultMixin, _usedTopLevelNames, i)); + _messageGenerators.add( + MessageGenerator.nested( + n, + this, + declaredMixins, + defaultMixin, + _usedTopLevelNames, + i, + ), + ); } // Extensions within messages won't create top-level classes and don't need @@ -111,8 +128,9 @@ class MessageGenerator extends ProtobufContainer { final usedExtensionNames = {...forbiddenExtensionNames}; for (var i = 0; i < _descriptor.extension.length; i++) { final x = _descriptor.extension[i]; - _extensionGenerators - .add(ExtensionGenerator.nested(x, this, usedExtensionNames, i)); + _extensionGenerators.add( + ExtensionGenerator.nested(x, this, usedExtensionNames, i), + ); } } @@ -126,24 +144,38 @@ class MessageGenerator extends ProtobufContainer { static const _messageFieldTag = 2; MessageGenerator.topLevel( - DescriptorProto descriptor, - ProtobufContainer parent, - Map declaredMixins, - PbMixin? defaultMixin, - Set usedNames, - int repeatedFieldIndex) - : this._(descriptor, parent, declaredMixins, defaultMixin, usedNames, - repeatedFieldIndex, _topLevelMessageTag); + DescriptorProto descriptor, + ProtobufContainer parent, + Map declaredMixins, + PbMixin? defaultMixin, + Set usedNames, + int repeatedFieldIndex, + ) : this._( + descriptor, + parent, + declaredMixins, + defaultMixin, + usedNames, + repeatedFieldIndex, + _topLevelMessageTag, + ); MessageGenerator.nested( - DescriptorProto descriptor, - ProtobufContainer parent, - Map declaredMixins, - PbMixin? defaultMixin, - Set usedNames, - int repeatedFieldIndex) - : this._(descriptor, parent, declaredMixins, defaultMixin, usedNames, - repeatedFieldIndex, _nestedMessageTag); + DescriptorProto descriptor, + ProtobufContainer parent, + Map declaredMixins, + PbMixin? defaultMixin, + Set usedNames, + int repeatedFieldIndex, + ) : this._( + descriptor, + parent, + declaredMixins, + defaultMixin, + usedNames, + repeatedFieldIndex, + _nestedMessageTag, + ); @override String get package => parent!.package; @@ -198,8 +230,11 @@ class MessageGenerator extends ProtobufContainer { final reserved = mixin?.findReservedNames() ?? const []; final members = messageMemberNames( - _descriptor, classname, _usedTopLevelNames, - reserved: reserved); + _descriptor, + classname, + _usedTopLevelNames, + reserved: reserved, + ); _fieldList = []; for (final names in members.fieldNames) { @@ -239,7 +274,9 @@ class MessageGenerator extends ProtobufContainer { /// For each .pb.dart file that the generated code needs to import, /// add its generator. void addImportsTo( - Set imports, Set enumImports) { + Set imports, + Set enumImports, + ) { checkResolved(); for (final field in _fieldList) { final typeGen = field.baseType.generator; @@ -292,29 +329,37 @@ class MessageGenerator extends ProtobufContainer { for (final oneof in _oneofNames) { OneofEnumGenerator.generate( - out, oneof.oneofEnumName, _oneofFields[oneof.index]); + out, + oneof.oneofEnumName, + _oneofFields[oneof.index], + ); } var mixinClause = ''; if (mixin != null) { - final mixinNames = - mixin!.findMixinsToApply().map((m) => '$mixinImportPrefix.${m.name}'); + final mixinNames = mixin!.findMixinsToApply().map( + (m) => '$mixinImportPrefix.${m.name}', + ); mixinClause = ' with ${mixinNames.join(", ")}'; } final omitMessageNames = ConditionalConstDefinition('omit_message_names'); out.addSuffix( - omitMessageNames.constFieldName, omitMessageNames.constDefinition); + omitMessageNames.constFieldName, + omitMessageNames.constDefinition, + ); - final conditionalPackageName = 'const $protobufImportPrefix.PackageName' + final conditionalPackageName = + 'const $protobufImportPrefix.PackageName' '(${omitMessageNames.createTernary(package)})'; final packageClause = package == '' ? '' : ', package: $conditionalPackageName'; - final proto3JsonClause = (mixin?.hasProto3JsonHelpers ?? false) - ? ', toProto3Json: $mixinImportPrefix.${mixin!.name}.toProto3JsonHelper, ' - 'fromProto3Json: $mixinImportPrefix.${mixin!.name}.fromProto3JsonHelper' - : ''; + final proto3JsonClause = + (mixin?.hasProto3JsonHelpers ?? false) + ? ', toProto3Json: $mixinImportPrefix.${mixin!.name}.toProto3JsonHelper, ' + 'fromProto3Json: $mixinImportPrefix.${mixin!.name}.fromProto3JsonHelper' + : ''; final String extendedClass; if (_descriptor.options.messageSetWireFormat) { @@ -329,115 +374,147 @@ class MessageGenerator extends ProtobufContainer { } if (_descriptor.options.deprecated) { out.println( - '@$coreImportPrefix.Deprecated(\'This message is deprecated\')'); + '@$coreImportPrefix.Deprecated(\'This message is deprecated\')', + ); } out.addAnnotatedBlock( - 'class $classname extends $protobufImportPrefix.$extendedClass$mixinClause {', - '}', [ - NamedLocation( - name: classname, fieldPathSegment: fieldPath, start: 'class '.length) - ], () { - _generateFactory(out); - - out.println(); - - out.printlnAnnotated('$classname._();', [ - NamedLocation(name: classname, fieldPathSegment: fieldPath, start: 0) - ]); - - out.println(); - - out.println( + 'class $classname extends $protobufImportPrefix.$extendedClass$mixinClause {', + '}', + [ + NamedLocation( + name: classname, + fieldPathSegment: fieldPath, + start: 'class '.length, + ), + ], + () { + _generateFactory(out); + + out.println(); + + out.printlnAnnotated('$classname._();', [ + NamedLocation(name: classname, fieldPathSegment: fieldPath, start: 0), + ]); + + out.println(); + + out.println( 'factory $classname.fromBuffer($coreImportPrefix.List<$coreImportPrefix.int> data,' ' [$protobufImportPrefix.ExtensionRegistry registry = $protobufImportPrefix.ExtensionRegistry.EMPTY])' - ' => create()..mergeFromBuffer(data, registry);'); - out.println('factory $classname.fromJson($coreImportPrefix.String json,' + ' => create()..mergeFromBuffer(data, registry);', + ); + out.println( + 'factory $classname.fromJson($coreImportPrefix.String json,' ' [$protobufImportPrefix.ExtensionRegistry registry = $protobufImportPrefix.ExtensionRegistry.EMPTY])' - ' => create()..mergeFromJson(json, registry);'); + ' => create()..mergeFromJson(json, registry);', + ); - out.println(); - for (final oneof in _oneofNames) { - out.addBlock( + out.println(); + for (final oneof in _oneofNames) { + out.addBlock( 'static const $coreImportPrefix.Map<$coreImportPrefix.int, ${oneof.oneofEnumName}> ${oneof.byTagMapName} = {', - '};', () { - for (final field in _oneofFields[oneof.index]) { - final oneofMemberName = - oneofEnumMemberName(field.memberNames!.fieldName); - out.println( - '${field.number} : ${oneof.oneofEnumName}.$oneofMemberName,'); - } - out.println('0 : ${oneof.oneofEnumName}.notSet'); - }); - } + '};', + () { + for (final field in _oneofFields[oneof.index]) { + final oneofMemberName = oneofEnumMemberName( + field.memberNames!.fieldName, + ); + out.println( + '${field.number} : ${oneof.oneofEnumName}.$oneofMemberName,', + ); + } + out.println('0 : ${oneof.oneofEnumName}.notSet'); + }, + ); + } - final omitMessageNames = ConditionalConstDefinition('omit_message_names'); - out.addSuffix( - omitMessageNames.constFieldName, omitMessageNames.constDefinition); + final omitMessageNames = ConditionalConstDefinition( + 'omit_message_names', + ); + out.addSuffix( + omitMessageNames.constFieldName, + omitMessageNames.constDefinition, + ); - out.addBlock( + out.addBlock( 'static final $protobufImportPrefix.BuilderInfo _i = ' '$protobufImportPrefix.BuilderInfo(${omitMessageNames.createTernary(messageName)}' '$packageClause' ', createEmptyInstance: create' '$proto3JsonClause)', - ';', () { - for (var oneof = 0; oneof < _oneofFields.length; oneof++) { - final tags = - _oneofFields[oneof].map((ProtobufField f) => f.number).toList(); - out.println('..oo($oneof, $tags)'); - } - - for (final field in _fieldList) { - field.generateBuilderInfoCall(out, package); - } + ';', + () { + for (var oneof = 0; oneof < _oneofFields.length; oneof++) { + final tags = + _oneofFields[oneof] + .map((ProtobufField f) => f.number) + .toList(); + out.println('..oo($oneof, $tags)'); + } + + for (final field in _fieldList) { + field.generateBuilderInfoCall(out, package); + } + + if (_descriptor.extensionRange.isNotEmpty) { + out.println('..hasExtensions = true'); + } + if (!_hasRequiredFields(this, {})) { + out.println('..hasRequiredFields = false'); + } + }, + ); - if (_descriptor.extensionRange.isNotEmpty) { - out.println('..hasExtensions = true'); - } - if (!_hasRequiredFields(this, {})) { - out.println('..hasRequiredFields = false'); + for (final x in _extensionGenerators) { + x.generate(out); } - }); - for (final x in _extensionGenerators) { - x.generate(out); - } - - out.println(); - out.println('@$coreImportPrefix.Deprecated(' - "'See https://github.com/google/protobuf.dart/issues/998.')"); - out.println( - '$classname clone() => $classname()..mergeFromMessage(this);'); - out.println('@$coreImportPrefix.Deprecated(' - "'See https://github.com/google/protobuf.dart/issues/998.')"); - out.println('$classname copyWith(void Function($classname) updates) =>' + out.println(); + out.println( + '@$coreImportPrefix.Deprecated(' + "'See https://github.com/google/protobuf.dart/issues/998.')", + ); + out.println( + '$classname clone() => $classname()..mergeFromMessage(this);', + ); + out.println( + '@$coreImportPrefix.Deprecated(' + "'See https://github.com/google/protobuf.dart/issues/998.')", + ); + out.println( + '$classname copyWith(void Function($classname) updates) =>' ' super.copyWith((message) => updates(message as $classname))' - ' as $classname;'); + ' as $classname;', + ); - out.println(); - out.println('@$coreImportPrefix.override'); - out.println('$protobufImportPrefix.BuilderInfo get info_ => _i;'); + out.println(); + out.println('@$coreImportPrefix.override'); + out.println('$protobufImportPrefix.BuilderInfo get info_ => _i;'); - // Factory functions which can be used as default value closures. - out.println(); - out.println("@$coreImportPrefix.pragma('dart2js:noInline')"); - out.println('static $classname create() => $classname._();'); - out.println('@$coreImportPrefix.override'); - out.println('$classname createEmptyInstance() => create();'); + // Factory functions which can be used as default value closures. + out.println(); + out.println("@$coreImportPrefix.pragma('dart2js:noInline')"); + out.println('static $classname create() => $classname._();'); + out.println('@$coreImportPrefix.override'); + out.println('$classname createEmptyInstance() => create();'); - out.println( + out.println( 'static $protobufImportPrefix.PbList<$classname> createRepeated() =>' - ' $protobufImportPrefix.PbList<$classname>();'); - out.println("@$coreImportPrefix.pragma('dart2js:noInline')"); - out.println('static $classname getDefault() =>' + ' $protobufImportPrefix.PbList<$classname>();', + ); + out.println("@$coreImportPrefix.pragma('dart2js:noInline')"); + out.println( + 'static $classname getDefault() =>' ' _defaultInstance ??=' ' $protobufImportPrefix.GeneratedMessage.\$_defaultFor<$classname>' - '(create);'); - out.println('static $classname? _defaultInstance;'); + '(create);', + ); + out.println('static $classname? _defaultInstance;'); - generateFieldsAccessorsMutators(out); - mixin?.injectHelpers(out); - }); + generateFieldsAccessorsMutators(out); + mixin?.injectHelpers(out); + }, + ); out.println(); } @@ -448,16 +525,19 @@ class MessageGenerator extends ProtobufContainer { _emitDeprecatedIf(field.isDeprecated, out); if (field.isRepeated && !field.isMapField) { out.println( - ' ${field.baseType.getRepeatedDartTypeIterable(fileGen)}? ${field.memberNames!.fieldName},'); + ' ${field.baseType.getRepeatedDartTypeIterable(fileGen)}? ${field.memberNames!.fieldName},', + ); } else if (field.isMapField) { final keyType = field.getDartMapKeyType(); final valueType = field.getDartMapValueType(); out.println( - ' $coreImportPrefix.Iterable<$coreImportPrefix.MapEntry<$keyType, $valueType>>? ' - '${field.memberNames!.fieldName},'); + ' $coreImportPrefix.Iterable<$coreImportPrefix.MapEntry<$keyType, $valueType>>? ' + '${field.memberNames!.fieldName},', + ); } else { out.println( - ' ${field.getDartType()}? ${field.memberNames!.fieldName},'); + ' ${field.getDartType()}? ${field.memberNames!.fieldName},', + ); } } out.print('}) '); @@ -473,13 +553,16 @@ class MessageGenerator extends ProtobufContainer { out.print('if (${field.memberNames!.fieldName} != null) '); if (field.isRepeated && !field.isMapField) { out.println( - '$result.${field.memberNames!.fieldName}.addAll(${field.memberNames!.fieldName});'); + '$result.${field.memberNames!.fieldName}.addAll(${field.memberNames!.fieldName});', + ); } else if (field.isMapField) { out.println( - '$result.${field.memberNames!.fieldName}.addEntries(${field.memberNames!.fieldName});'); + '$result.${field.memberNames!.fieldName}.addEntries(${field.memberNames!.fieldName});', + ); } else { out.println( - '$result.${field.memberNames!.fieldName} = ${field.memberNames!.fieldName};'); + '$result.${field.memberNames!.fieldName} = ${field.memberNames!.fieldName};', + ); } } out.println('return $result;'); @@ -546,14 +629,21 @@ class MessageGenerator extends ProtobufContainer { void generateOneofAccessors(IndentingWriter out, OneofNames oneof) { out.println(); - out.println('${oneof.oneofEnumName} ${oneof.whichOneofMethodName}() ' - '=> ${oneof.byTagMapName}[\$_whichOneof(${oneof.index})]!;'); - out.println('void ${oneof.clearMethodName}() ' - '=> \$_clearField(\$_whichOneof(${oneof.index}));'); + out.println( + '${oneof.oneofEnumName} ${oneof.whichOneofMethodName}() ' + '=> ${oneof.byTagMapName}[\$_whichOneof(${oneof.index})]!;', + ); + out.println( + 'void ${oneof.clearMethodName}() ' + '=> \$_clearField(\$_whichOneof(${oneof.index}));', + ); } void generateFieldAccessorsMutators( - ProtobufField field, IndentingWriter out, List memberFieldPath) { + ProtobufField field, + IndentingWriter out, + List memberFieldPath, + ) { final fieldTypeString = field.getDartType(); final defaultExpr = field.getDefaultExpr(); final names = field.memberNames; @@ -566,16 +656,24 @@ class MessageGenerator extends ProtobufContainer { _emitDeprecatedIf(field.isDeprecated, out); _emitOverrideIf(field.overridesGetter, out); _emitIndexAnnotation(field.number, out); - final getterExpr = _getterExpression(fieldTypeString, field.index!, - defaultExpr, field.isRepeated, field.isMapField); + final getterExpr = _getterExpression( + fieldTypeString, + field.index!, + defaultExpr, + field.isRepeated, + field.isMapField, + ); out.printlnAnnotated( - '$fieldTypeString get ${names!.fieldName} => $getterExpr;', [ - NamedLocation( + '$fieldTypeString get ${names!.fieldName} => $getterExpr;', + [ + NamedLocation( name: names.fieldName, fieldPathSegment: memberFieldPath, - start: '$fieldTypeString get '.length) - ]); + start: '$fieldTypeString get '.length, + ), + ], + ); if (field.isRepeated) { if (field.overridesSetter) { @@ -601,9 +699,10 @@ class MessageGenerator extends ProtobufContainer { '$fastSetter(${field.index}, value);', [ NamedLocation( - name: names.fieldName, - fieldPathSegment: memberFieldPath, - start: 'set '.length) + name: names.fieldName, + fieldPathSegment: memberFieldPath, + start: 'set '.length, + ), ], ); } else { @@ -612,9 +711,10 @@ class MessageGenerator extends ProtobufContainer { '\$_setField(${field.number}, value);', [ NamedLocation( - name: names.fieldName, - fieldPathSegment: memberFieldPath, - start: 'set '.length) + name: names.fieldName, + fieldPathSegment: memberFieldPath, + start: 'set '.length, + ), ], ); } @@ -623,45 +723,56 @@ class MessageGenerator extends ProtobufContainer { _emitOverrideIf(field.overridesHasMethod, out); _emitIndexAnnotation(field.number, out); out.printlnAnnotated( - '$coreImportPrefix.bool ${names.hasMethodName}() =>' - ' \$_has(${field.index});', - [ - NamedLocation( - name: names.hasMethodName!, - fieldPathSegment: memberFieldPath, - start: '$coreImportPrefix.bool '.length) - ]); + '$coreImportPrefix.bool ${names.hasMethodName}() =>' + ' \$_has(${field.index});', + [ + NamedLocation( + name: names.hasMethodName!, + fieldPathSegment: memberFieldPath, + start: '$coreImportPrefix.bool '.length, + ), + ], + ); } _emitDeprecatedIf(field.isDeprecated, out); _emitOverrideIf(field.overridesClearMethod, out); _emitIndexAnnotation(field.number, out); out.printlnAnnotated( - 'void ${names.clearMethodName}() =>' - ' \$_clearField(${field.number});', - [ - NamedLocation( - name: names.clearMethodName!, - fieldPathSegment: memberFieldPath, - start: 'void '.length) - ]); + 'void ${names.clearMethodName}() =>' + ' \$_clearField(${field.number});', + [ + NamedLocation( + name: names.clearMethodName!, + fieldPathSegment: memberFieldPath, + start: 'void '.length, + ), + ], + ); if (field.baseType.isMessage) { _emitDeprecatedIf(field.isDeprecated, out); _emitIndexAnnotation(field.number, out); out.printlnAnnotated( - '$fieldTypeString ${names.ensureMethodName}() => ' - '\$_ensure(${field.index});', - [ - NamedLocation( - name: names.ensureMethodName!, - fieldPathSegment: memberFieldPath, - start: '$fieldTypeString '.length) - ]); + '$fieldTypeString ${names.ensureMethodName}() => ' + '\$_ensure(${field.index});', + [ + NamedLocation( + name: names.ensureMethodName!, + fieldPathSegment: memberFieldPath, + start: '$fieldTypeString '.length, + ), + ], + ); } } } - String _getterExpression(String fieldType, int index, String defaultExpr, - bool isRepeated, bool isMapField) { + String _getterExpression( + String fieldType, + int index, + String defaultExpr, + bool isRepeated, + bool isMapField, + ) { if (isMapField) { return '\$_getMap($index)'; } @@ -695,7 +806,8 @@ class MessageGenerator extends ProtobufContainer { void _emitDeprecatedIf(bool condition, IndentingWriter out) { if (condition) { out.println( - '@$coreImportPrefix.Deprecated(\'This field is deprecated.\')'); + '@$coreImportPrefix.Deprecated(\'This field is deprecated.\')', + ); } } @@ -735,8 +847,10 @@ class MessageGenerator extends ProtobufContainer { final nestedEnumNames = _enumGenerators.map((e) => e.getJsonConstant(fileGen)).toList(); - out.println('@$coreImportPrefix.Deprecated' - '(\'Use ${toplevelParent!.binaryDescriptorName} instead\')'); + out.println( + '@$coreImportPrefix.Deprecated' + '(\'Use ${toplevelParent!.binaryDescriptorName} instead\')', + ); out.addBlock('const $name = {', '};', () { for (final key in json.keys) { out.print("'$key': "); @@ -769,7 +883,9 @@ class MessageGenerator extends ProtobufContainer { /// First searches [_wellKnownMixins], then [declaredMixins], /// then internal mixins declared by [findMixin]. PbMixin? _getMixin( - Map declaredMixins, PbMixin? defaultMixin) { + Map declaredMixins, + PbMixin? defaultMixin, + ) { final wellKnownMixin = wellKnownMixinForFullName(fullName); if (wellKnownMixin != null) return wellKnownMixin; if (!_descriptor.hasOptions() || diff --git a/protoc_plugin/lib/src/options.dart b/protoc_plugin/lib/src/options.dart index a923373b2..23b400488 100644 --- a/protoc_plugin/lib/src/options.dart +++ b/protoc_plugin/lib/src/options.dart @@ -11,8 +11,11 @@ typedef OnError = void Function(String details); /// key-value pair ("name=value"). For each option "name", it looks up whether a /// [SingleOptionParser] exists in [parsers] and delegates the actual parsing of /// the option to it. Returns `true` if no errors were reported. -bool genericOptionsParser(CodeGeneratorRequest request, - CodeGeneratorResponse response, Map parsers) { +bool genericOptionsParser( + CodeGeneratorRequest request, + CodeGeneratorResponse response, + Map parsers, +) { final parameter = request.parameter; final options = parameter.trim().split(','); final errors = []; @@ -52,10 +55,11 @@ class GenerationOptions { final bool generateMetadata; final bool disableConstructorArgs; - GenerationOptions( - {this.useGrpc = false, - this.generateMetadata = false, - this.disableConstructorArgs = false}); + GenerationOptions({ + this.useGrpc = false, + this.generateMetadata = false, + this.disableConstructorArgs = false, + }); } /// A parser for a name-value pair option. Options parsed in @@ -112,8 +116,10 @@ class DisableConstructorArgsParser implements SingleOptionParser { /// [GrpcOptionParser]) and any additional option added in [parsers]. If /// [parsers] has a key for `rpc`, it will be ignored. GenerationOptions? parseGenerationOptions( - CodeGeneratorRequest request, CodeGeneratorResponse response, - [Map? parsers]) { + CodeGeneratorRequest request, + CodeGeneratorResponse response, [ + Map? parsers, +]) { final newParsers = {}; if (parsers != null) newParsers.addAll(parsers); @@ -128,9 +134,10 @@ GenerationOptions? parseGenerationOptions( if (genericOptionsParser(request, response, newParsers)) { return GenerationOptions( - useGrpc: grpcOptionParser.grpcEnabled, - generateMetadata: generateMetadataParser.generateKytheInfo, - disableConstructorArgs: disableConstructorArgsParser.value); + useGrpc: grpcOptionParser.grpcEnabled, + generateMetadata: generateMetadataParser.generateKytheInfo, + disableConstructorArgs: disableConstructorArgsParser.value, + ); } return null; } diff --git a/protoc_plugin/lib/src/output_config.dart b/protoc_plugin/lib/src/output_config.dart index 0faa00509..9ef88c368 100644 --- a/protoc_plugin/lib/src/output_config.dart +++ b/protoc_plugin/lib/src/output_config.dart @@ -41,8 +41,9 @@ class DefaultOutputConfiguration extends OutputConfiguration { Uri resolveImport(Uri target, Uri source, String extension) { final targetPath = path.url.fromUri(target); final sourceDir = path.url.dirname(path.url.fromUri(source)); - final base = - path.withoutExtension(path.url.relative(targetPath, from: sourceDir)); + final base = path.withoutExtension( + path.url.relative(targetPath, from: sourceDir), + ); return path.url.toUri('$base$extension'); } } diff --git a/protoc_plugin/lib/src/protobuf_field.dart b/protoc_plugin/lib/src/protobuf_field.dart index 5ea7ec0e2..af3ec5921 100644 --- a/protoc_plugin/lib/src/protobuf_field.dart +++ b/protoc_plugin/lib/src/protobuf_field.dart @@ -5,17 +5,22 @@ part of '../protoc.dart'; class ProtobufField { - static final RegExp _hexLiteralRegex = - RegExp(r'^0x[0-9a-f]+$', multiLine: false, caseSensitive: false); + static final RegExp _hexLiteralRegex = RegExp( + r'^0x[0-9a-f]+$', + multiLine: false, + caseSensitive: false, + ); static final RegExp _integerLiteralRegex = RegExp(r'^[+-]?[0-9]+$'); static final RegExp _decimalLiteralRegexA = RegExp( - r'^[+-]?([0-9]*)\.[0-9]+(e[+-]?[0-9]+)?$', - multiLine: false, - caseSensitive: false); + r'^[+-]?([0-9]*)\.[0-9]+(e[+-]?[0-9]+)?$', + multiLine: false, + caseSensitive: false, + ); static final RegExp _decimalLiteralRegexB = RegExp( - r'^[+-]?[0-9]+e[+-]?[0-9]+$', - multiLine: false, - caseSensitive: false); + r'^[+-]?[0-9]+e[+-]?[0-9]+$', + multiLine: false, + caseSensitive: false, + ); final FieldDescriptorProto descriptor; @@ -27,18 +32,25 @@ class ProtobufField { final ProtobufContainer parent; ProtobufField.message( - FieldNames names, ProtobufContainer parent, GenerationContext ctx) - : this._(names.descriptor, names, parent, ctx); - - ProtobufField.extension(FieldDescriptorProto descriptor, - ProtobufContainer parent, GenerationContext ctx) - : this._(descriptor, null, parent, ctx); - - ProtobufField._(this.descriptor, FieldNames? dartNames, this.parent, - GenerationContext ctx) - : memberNames = dartNames, - fullName = '${parent.fullName}.${descriptor.name}', - baseType = BaseType(descriptor, ctx); + FieldNames names, + ProtobufContainer parent, + GenerationContext ctx, + ) : this._(names.descriptor, names, parent, ctx); + + ProtobufField.extension( + FieldDescriptorProto descriptor, + ProtobufContainer parent, + GenerationContext ctx, + ) : this._(descriptor, null, parent, ctx); + + ProtobufField._( + this.descriptor, + FieldNames? dartNames, + this.parent, + GenerationContext ctx, + ) : memberNames = dartNames, + fullName = '${parent.fullName}.${descriptor.name}', + baseType = BaseType(descriptor, ctx); /// The index of this field in MessageGenerator.fieldList. /// @@ -154,9 +166,7 @@ class ProtobufField { /// Only for map fields: returns the type to use for Dart map field key type. String getDartMapKeyType() { assert(isMapField); - return (baseType.generator as MessageGenerator) - ._fieldList[0] - .baseType + return (baseType.generator as MessageGenerator)._fieldList[0].baseType .getDartType(parent.fileGen!); } @@ -164,9 +174,7 @@ class ProtobufField { /// type. String getDartMapValueType() { assert(isMapField); - return (baseType.generator as MessageGenerator) - ._fieldList[1] - .baseType + return (baseType.generator as MessageGenerator)._fieldList[1].baseType .getDartType(parent.fileGen!); } @@ -187,7 +195,9 @@ class ProtobufField { } static String _formatArguments( - List positionals, Map named) { + List positionals, + Map named, + ) { final args = positionals.toList(); named.forEach((key, value) { if (value != null) { @@ -204,7 +214,9 @@ class ProtobufField { final omitFieldNames = ConditionalConstDefinition('omit_field_names'); out.addSuffix( - omitFieldNames.constFieldName, omitFieldNames.constDefinition); + omitFieldNames.constFieldName, + omitFieldNames.constDefinition, + ); final quotedName = omitFieldNames.createTernary(descriptor.jsonName); final type = baseType.getDartType(parent.fileGen!); @@ -443,11 +455,13 @@ class ProtobufField { bool _hasBooleanOption(Extension extension) => descriptor.options.getExtension(extension) as bool? ?? false; - String get _invalidDefaultValue => 'dart-protoc-plugin:' + String get _invalidDefaultValue => + 'dart-protoc-plugin:' ' invalid default value (${descriptor.defaultValue})' ' found in field $fullName'; - String _typeNotImplemented(String methodName) => 'dart-protoc-plugin:' + String _typeNotImplemented(String methodName) => + 'dart-protoc-plugin:' ' $methodName not implemented for type (${descriptor.type})' ' found in field $fullName'; @@ -455,6 +469,8 @@ class ProtobufField { static String _unCamelCase(String name) { return name.replaceAllMapped( - _upperCase, (match) => '_${match.group(0)!.toLowerCase()}'); + _upperCase, + (match) => '_${match.group(0)!.toLowerCase()}', + ); } } diff --git a/protoc_plugin/lib/src/service_generator.dart b/protoc_plugin/lib/src/service_generator.dart index 46a0c4bf3..bc26c115f 100644 --- a/protoc_plugin/lib/src/service_generator.dart +++ b/protoc_plugin/lib/src/service_generator.dart @@ -38,10 +38,11 @@ class ServiceGenerator { } ServiceGenerator(this._descriptor, this.fileGen, Set usedNames) - : classname = disambiguateName( - serviceBaseName(avoidInitialUnderscore(_descriptor.name)), - usedNames, - defaultSuffixes()); + : classname = disambiguateName( + serviceBaseName(avoidInitialUnderscore(_descriptor.name)), + usedNames, + defaultSuffixes(), + ); /// Finds all message types used by this service. /// @@ -86,7 +87,9 @@ class ServiceGenerator { for (final field in mg._fieldList) { if (field.baseType.isGroup || field.baseType.isMessage) { _addDepsRecursively( - field.baseType.generator as MessageGenerator, depth + 1); + field.baseType.generator as MessageGenerator, + depth + 1, + ); } } } @@ -143,8 +146,10 @@ class ServiceGenerator { final inputClass = _getDartClassName(m.inputType); final outputClass = _getDartClassName(m.outputType); - out.println('$_future<$outputClass> $methodName(' - '$_serverContext ctx, $inputClass request);'); + out.println( + '$_future<$outputClass> $methodName(' + '$_serverContext ctx, $inputClass request);', + ); } void _generateStubs(IndentingWriter out) { @@ -156,36 +161,46 @@ class ServiceGenerator { void _generateRequestMethod(IndentingWriter out) { out.addBlock( - '$_generatedMessage createRequest($coreImportPrefix.String methodName) {', - '}', () { - out.addBlock('switch (methodName) {', '}', () { - for (final m in _methodDescriptors) { - final inputClass = _getDartClassName(m.inputType); - out.println("case '${m.name}': return $inputClass();"); - } - out.println('default: ' - "throw $coreImportPrefix.ArgumentError('Unknown method: \$methodName');"); - }); - }); + '$_generatedMessage createRequest($coreImportPrefix.String methodName) {', + '}', + () { + out.addBlock('switch (methodName) {', '}', () { + for (final m in _methodDescriptors) { + final inputClass = _getDartClassName(m.inputType); + out.println("case '${m.name}': return $inputClass();"); + } + out.println( + 'default: ' + "throw $coreImportPrefix.ArgumentError('Unknown method: \$methodName');", + ); + }); + }, + ); out.println(); } void _generateDispatchMethod(IndentingWriter out) { out.addBlock( - '$_future<$_generatedMessage> handleCall($_serverContext ctx, ' - '$coreImportPrefix.String methodName, $_generatedMessage request) {', - '}', () { - out.addBlock('switch (methodName) {', '}', () { - for (final m in _methodDescriptors) { - final methodName = _methodName(m.name); - final inputClass = _getDartClassName(m.inputType); - out.println("case '${m.name}': " - 'return $methodName(ctx, request as $inputClass);'); - } - out.println('default: throw $coreImportPrefix.ArgumentError(' - "'Unknown method: \$methodName');"); - }); - }); + '$_future<$_generatedMessage> handleCall($_serverContext ctx, ' + '$coreImportPrefix.String methodName, $_generatedMessage request) {', + '}', + () { + out.addBlock('switch (methodName) {', '}', () { + for (final m in _methodDescriptors) { + final methodName = _methodName(m.name); + final inputClass = _getDartClassName(m.inputType); + out.println( + "case '${m.name}': " + 'return $methodName(ctx, request as $inputClass);', + ); + } + out.println( + 'default: throw $coreImportPrefix.ArgumentError(' + "'Unknown method: \$methodName');", + ); + }); + }, + ); out.println(); } @@ -194,19 +209,23 @@ class ServiceGenerator { void generate(IndentingWriter out) { out.addBlock( - 'abstract class $classname extends ' - '$_parentClass {', - '}', () { - _generateStubs(out); - _generateRequestMethod(out); - _generateDispatchMethod(out); - _generateMoreClassMembers(out); - out.println( - '$coreImportPrefix.Map<$coreImportPrefix.String, $coreImportPrefix.dynamic> get \$json => $jsonConstant;'); - out.println( + 'abstract class $classname extends ' + '$_parentClass {', + '}', + () { + _generateStubs(out); + _generateRequestMethod(out); + _generateDispatchMethod(out); + _generateMoreClassMembers(out); + out.println( + '$coreImportPrefix.Map<$coreImportPrefix.String, $coreImportPrefix.dynamic> get \$json => $jsonConstant;', + ); + out.println( '$coreImportPrefix.Map<$coreImportPrefix.String, $coreImportPrefix.Map<$coreImportPrefix.String,' - ' $coreImportPrefix.dynamic>> get \$messageJson => $messageJsonConstant;'); - }); + ' $coreImportPrefix.dynamic>> get \$messageJson => $messageJsonConstant;', + ); + }, + ); out.println(); } @@ -218,8 +237,10 @@ class ServiceGenerator { /// The map includes an entry for every message type that might need /// to be read or written (assuming the type name resolved). void generateConstants(IndentingWriter out) { - out.print('const $coreImportPrefix.Map<$coreImportPrefix.String,' - ' $coreImportPrefix.dynamic> $jsonConstant = '); + out.print( + 'const $coreImportPrefix.Map<$coreImportPrefix.String,' + ' $coreImportPrefix.dynamic> $jsonConstant = ', + ); writeJsonConst(out, _descriptor.writeToJsonMap()); out.println(';'); out.println(); @@ -229,18 +250,22 @@ class ServiceGenerator { typeConstants[key] = _transitiveDeps[key]!.getJsonConstant(fileGen); } - out.println('@$coreImportPrefix.Deprecated' - '(\'Use $binaryDescriptorName instead\')'); + out.println( + '@$coreImportPrefix.Deprecated' + '(\'Use $binaryDescriptorName instead\')', + ); out.addBlock( - 'const $coreImportPrefix.Map<$coreImportPrefix.String,' - ' $coreImportPrefix.Map<$coreImportPrefix.String,' - ' $coreImportPrefix.dynamic>> $messageJsonConstant = {', - '};', () { - for (final key in typeConstants.keys) { - final typeConst = typeConstants[key]; - out.println("'$key': $typeConst,"); - } - }); + 'const $coreImportPrefix.Map<$coreImportPrefix.String,' + ' $coreImportPrefix.Map<$coreImportPrefix.String,' + ' $coreImportPrefix.dynamic>> $messageJsonConstant = {', + '};', + () { + for (final key in typeConstants.keys) { + final typeConst = typeConstants[key]; + out.println("'$key': $typeConst,"); + } + }, + ); out.println(); if (_undefinedDeps.isNotEmpty) { diff --git a/protoc_plugin/lib/src/shared.dart b/protoc_plugin/lib/src/shared.dart index 89fa1d1f9..6730c761a 100644 --- a/protoc_plugin/lib/src/shared.dart +++ b/protoc_plugin/lib/src/shared.dart @@ -79,9 +79,12 @@ String? toDartComment(String value) { if (leadingSpaces != null) { final prefix = leadingSpaces.group(0)!; if (lines.every((line) => line.isEmpty || line.startsWith(prefix))) { - lines = lines - .map((line) => line.isEmpty ? line : line.substring(prefix.length)) - .toList(); + lines = + lines + .map( + (line) => line.isEmpty ? line : line.substring(prefix.length), + ) + .toList(); } } diff --git a/protoc_plugin/lib/src/well_known_types.dart b/protoc_plugin/lib/src/well_known_types.dart index f9ee9090b..3b3222390 100644 --- a/protoc_plugin/lib/src/well_known_types.dart +++ b/protoc_plugin/lib/src/well_known_types.dart @@ -11,10 +11,11 @@ const _wellKnownImportPath = 'package:protobuf/src/protobuf/mixins/well_known.dart'; const _wellKnownMixins = { - 'google.protobuf.Any': PbMixin('AnyMixin', - importFrom: _wellKnownImportPath, - injectedHelpers: [ - ''' + 'google.protobuf.Any': PbMixin( + 'AnyMixin', + importFrom: _wellKnownImportPath, + injectedHelpers: [ + ''' /// Creates a new [Any] encoding [message]. /// /// The [typeUrl] will be [typeUrlPrefix]/`fullName` where `fullName` is @@ -25,13 +26,15 @@ static Any pack($protobufImportPrefix.GeneratedMessage message, $mixinImportPrefix.AnyMixin.packIntoAny(result, message, typeUrlPrefix: typeUrlPrefix); return result; -}''' - ], - hasProto3JsonHelpers: true), - 'google.protobuf.Timestamp': PbMixin('TimestampMixin', - importFrom: _wellKnownImportPath, - injectedHelpers: [ - ''' +}''', + ], + hasProto3JsonHelpers: true, + ), + 'google.protobuf.Timestamp': PbMixin( + 'TimestampMixin', + importFrom: _wellKnownImportPath, + injectedHelpers: [ + ''' /// Creates a new instance from [dateTime]. /// /// Time zone information will not be preserved. @@ -39,9 +42,10 @@ static Timestamp fromDateTime($coreImportPrefix.DateTime dateTime) { final result = create(); $mixinImportPrefix.TimestampMixin.setFromDateTime(result, dateTime); return result; -}''' - ], - hasProto3JsonHelpers: true), +}''', + ], + hasProto3JsonHelpers: true, + ), 'google.protobuf.Duration': PbMixin( 'DurationMixin', importFrom: _wellKnownImportPath, @@ -129,5 +133,5 @@ static Duration fromDart($coreImportPrefix.Duration duration) => Duration() 'FieldMaskMixin', importFrom: _wellKnownImportPath, hasProto3JsonHelpers: true, - ) + ), }; diff --git a/protoc_plugin/pubspec.yaml b/protoc_plugin/pubspec.yaml index 2ffd36700..f6cf1ba7f 100644 --- a/protoc_plugin/pubspec.yaml +++ b/protoc_plugin/pubspec.yaml @@ -1,10 +1,10 @@ name: protoc_plugin -version: 22.4.0 +version: 22.4.1-wip description: A protobuf protoc compiler plugin used to generate Dart code. repository: https://github.com/google/protobuf.dart/tree/master/protoc_plugin environment: - sdk: ^3.6.0 + sdk: ^3.7.0 resolution: workspace @@ -15,7 +15,7 @@ dependencies: protobuf: ^4.1.0 dev_dependencies: - dart_style: ^3.0.0 + dart_style: ^3.1.0 lints: '>=5.0.0 <7.0.0' pub_semver: ^2.2.0 test: ^1.16.0 diff --git a/protoc_plugin/test/any_test.dart b/protoc_plugin/test/any_test.dart index 6082f3e2a..6164e0715 100644 --- a/protoc_plugin/test/any_test.dart +++ b/protoc_plugin/test/any_test.dart @@ -14,8 +14,10 @@ void main() { test('pack -> unpack', () { final any = Any.pack(SearchRequest()..query = 'hest'); expect(any.typeUrl, 'type.googleapis.com/service.SearchRequest'); - final any1 = Any.pack(SearchRequest()..query = 'hest1', - typeUrlPrefix: 'example.com'); + final any1 = Any.pack( + SearchRequest()..query = 'hest1', + typeUrlPrefix: 'example.com', + ); expect(any1.typeUrl, 'example.com/service.SearchRequest'); expect(any1.canUnpackInto(SearchRequest.getDefault()), true); expect(any1.canUnpackInto(SearchResponse.getDefault()), false); @@ -34,14 +36,18 @@ void main() { expect(any.canUnpackInto(Any.getDefault()), true); expect(any.canUnpackInto(SearchRequest.getDefault()), false); expect( - any.unpackInto(Any()).canUnpackInto(SearchRequest.getDefault()), true); + any.unpackInto(Any()).canUnpackInto(SearchRequest.getDefault()), + true, + ); expect(any.unpackInto(Any()).unpackInto(SearchRequest()).query, 'hest'); }); test('toplevel', () { - final any = Any.pack(toplevel.T() - ..a = 127 - ..b = 'hest'); + final any = Any.pack( + toplevel.T() + ..a = 127 + ..b = 'hest', + ); expect(any.typeUrl, 'type.googleapis.com/toplevel.T'); final t2 = any.unpackInto(toplevel.T()); expect(t2.a, 127); @@ -51,7 +57,9 @@ void main() { test('nested message', () { final any = Any.pack(Container_Nested()..int32Value = 127); expect( - any.typeUrl, 'type.googleapis.com/protobuf_unittest.Container.Nested'); + any.typeUrl, + 'type.googleapis.com/protobuf_unittest.Container.Nested', + ); final t2 = any.unpackInto(Container_Nested()); expect(t2.int32Value, 127); }); @@ -60,17 +68,22 @@ void main() { final any = Any.pack(SearchRequest()..query = 'hest'); final any1 = Any.pack(SearchRequest()..query = 'hest1'); final any2 = Any.pack(SearchRequest()..query = 'hest2'); - final testAny = TestAny() - ..anyValue = any - ..repeatedAnyValue.addAll([any1, any2]); + final testAny = + TestAny() + ..anyValue = any + ..repeatedAnyValue.addAll([any1, any2]); final testAnyFromBuffer = TestAny.fromBuffer(testAny.writeToBuffer()); expect( - testAnyFromBuffer.anyValue.unpackInto(SearchRequest()).query, 'hest'); + testAnyFromBuffer.anyValue.unpackInto(SearchRequest()).query, + 'hest', + ); expect( - testAnyFromBuffer.repeatedAnyValue[0].unpackInto(SearchRequest()).query, - 'hest1'); + testAnyFromBuffer.repeatedAnyValue[0].unpackInto(SearchRequest()).query, + 'hest1', + ); expect( - testAnyFromBuffer.repeatedAnyValue[1].unpackInto(SearchRequest()).query, - 'hest2'); + testAnyFromBuffer.repeatedAnyValue[1].unpackInto(SearchRequest()).query, + 'hest2', + ); }); } diff --git a/protoc_plugin/test/bazel_test.dart b/protoc_plugin/test/bazel_test.dart index 994687fb0..68894f07f 100644 --- a/protoc_plugin/test/bazel_test.dart +++ b/protoc_plugin/test/bazel_test.dart @@ -50,9 +50,10 @@ void main() { test('should handle multiple package|path entries', () { optionParser.parse( - optionName, - 'foo|bar/baz|wibble/wobble;a|b/c/d|e/f;one.two|three|four/five', - onError); + optionName, + 'foo|bar/baz|wibble/wobble;a|b/c/d|e/f;one.two|three|four/five', + onError, + ); expect(errors, isEmpty); expect(packages.length, 3); expect(packages['bar/baz']!.name, 'foo'); @@ -67,8 +68,11 @@ void main() { }); test('should skip and continue past malformed entries', () { - optionParser.parse(optionName, - 'foo|bar/baz|wibble/wobble;fizz;a.b|c/d|e/f;x|y|zz|y', onError); + optionParser.parse( + optionName, + 'foo|bar/baz|wibble/wobble;fizz;a.b|c/d|e/f;x|y|zz|y', + onError, + ); expect(errors.length, 2); expect(packages.length, 2); expect(packages['bar/baz']!.name, 'foo'); @@ -76,16 +80,22 @@ void main() { }); test('should emit error for conflicting package names', () { - optionParser.parse(optionName, - 'foo|bar/baz|wibble/wobble;flob|bar/baz|wibble/wobble', onError); + optionParser.parse( + optionName, + 'foo|bar/baz|wibble/wobble;flob|bar/baz|wibble/wobble', + onError, + ); expect(errors.length, 1); expect(packages.length, 1); expect(packages['bar/baz']!.name, 'foo'); }); test('should emit error for conflicting outputRoots', () { - optionParser.parse(optionName, - 'foo|bar/baz|wibble/wobble;foo|bar/baz|womble/wumble', onError); + optionParser.parse( + optionName, + 'foo|bar/baz|wibble/wobble;foo|bar/baz|womble/wumble', + onError, + ); expect(errors.length, 1); expect(packages.length, 1); expect(packages['bar/baz']!.outputRoot, 'wibble/wobble'); @@ -93,7 +103,10 @@ void main() { test('should normalize paths', () { optionParser.parse( - optionName, 'foo|bar//baz/|quux/;a|b/|c;c|d//e/f///|g//h//', onError); + optionName, + 'foo|bar//baz/|quux/;a|b/|c;c|d//e/f///|g//h//', + onError, + ); expect(errors, isEmpty); expect(packages.length, 3); expect(packages['bar/baz']!.name, 'foo'); @@ -116,42 +129,53 @@ void main() { packages = { 'foo/bar': BazelPackage('a.b.c', 'foo/bar', 'baz/flob'), 'foo/bar/baz': BazelPackage('d.e.f', 'foo/bar/baz', 'baz/flob/foo'), - 'wibble/wobble': - BazelPackage('wibble.wobble', 'wibble/wobble', 'womble/wumble'), + 'wibble/wobble': BazelPackage( + 'wibble.wobble', + 'wibble/wobble', + 'womble/wumble', + ), }; config = BazelOutputConfiguration(packages); }); group('outputPathForUri', () { test('should handle files at package root', () { - final p = - config.outputPathFor(Uri.parse('foo/bar/quux.proto'), '.pb.dart'); + final p = config.outputPathFor( + Uri.parse('foo/bar/quux.proto'), + '.pb.dart', + ); expect(p.path, 'baz/flob/quux.pb.dart'); }); test('should handle files below package root', () { final p = config.outputPathFor( - Uri.parse('foo/bar/a/b/quux.proto'), '.pb.dart'); + Uri.parse('foo/bar/a/b/quux.proto'), + '.pb.dart', + ); expect(p.path, 'baz/flob/a/b/quux.pb.dart'); }); test('should handle files in a nested package root', () { final p = config.outputPathFor( - Uri.parse('foo/bar/baz/quux.proto'), '.pb.dart'); + Uri.parse('foo/bar/baz/quux.proto'), + '.pb.dart', + ); expect(p.path, 'baz/flob/foo/quux.pb.dart'); }); test('should handle files below a nested package root', () { final p = config.outputPathFor( - Uri.parse('foo/bar/baz/a/b/quux.proto'), '.pb.dart'); + Uri.parse('foo/bar/baz/a/b/quux.proto'), + '.pb.dart', + ); expect(p.path, 'baz/flob/foo/a/b/quux.pb.dart'); }); test('should throw if unable to locate the package for an input', () { expect( - () => - config.outputPathFor(Uri.parse('a/b/c/quux.proto'), '.pb.dart'), - throwsArgumentError); + () => config.outputPathFor(Uri.parse('a/b/c/quux.proto'), '.pb.dart'), + throwsArgumentError, + ); }); }); @@ -196,8 +220,10 @@ void main() { test('should throw if target is in unknown package', () { final target = Uri.parse('flob/flub/quux.proto'); final source = Uri.parse('foo/bar/baz.proto'); - expect(() => config.resolveImport(target, source, '.pb.dart'), - throwsA(startsWith('ERROR: cannot generate import for'))); + expect( + () => config.resolveImport(target, source, '.pb.dart'), + throwsA(startsWith('ERROR: cannot generate import for')), + ); }); }); }); diff --git a/protoc_plugin/test/client_generator_test.dart b/protoc_plugin/test/client_generator_test.dart index 88f617444..40ac61fb0 100644 --- a/protoc_plugin/test/client_generator_test.dart +++ b/protoc_plugin/test/client_generator_test.dart @@ -14,13 +14,17 @@ import 'src/service_util.dart'; void main() { test('testClientGenerator', () { final options = GenerationOptions(); - final fd = buildFileDescriptor( - 'testpkg', 'testpkg.proto', ['SomeRequest', 'SomeReply']); + final fd = buildFileDescriptor('testpkg', 'testpkg.proto', [ + 'SomeRequest', + 'SomeReply', + ]); fd.service.add(buildServiceDescriptor()); final fg = FileGenerator(fd, options); - final fd2 = buildFileDescriptor( - 'foo.bar', 'foobar.proto', ['EmptyMessage', 'AnotherReply']); + final fd2 = buildFileDescriptor('foo.bar', 'foobar.proto', [ + 'EmptyMessage', + 'AnotherReply', + ]); final fg2 = FileGenerator(fd2, options); link(GenerationOptions(), [fg, fg2]); diff --git a/protoc_plugin/test/const_generator_test.dart b/protoc_plugin/test/const_generator_test.dart index 2e423a76a..9760011d4 100644 --- a/protoc_plugin/test/const_generator_test.dart +++ b/protoc_plugin/test/const_generator_test.dart @@ -28,37 +28,44 @@ void main() { expect(toConst(r'hello $world'), r"'hello \$world'"); expect(toConst("She said, 'hello.'"), r"'She said, \'hello.\''"); expect(toConst('single: \' double: "'), r"""'single: \' double: "'"""); - expect(toConst("""single: ' double: '' triple: '''"""), - r"'single: \' double: \'\' triple: \'\'\''"); - expect(toConst("""single: ' double: " triples: ''' and \"\"\"!"""), - r"""'single: \' double: " triples: \'\'\' and """ '"""!\''); + expect( + toConst("""single: ' double: '' triple: '''"""), + r"'single: \' double: \'\' triple: \'\'\''", + ); + expect( + toConst("""single: ' double: " triples: ''' and \"\"\"!"""), + r"""'single: \' double: " triples: \'\'\' and """ + '"""!\'', + ); }); test('writeJsonConst list examples', () { expect(toConst([]), '[]'); expect(toConst([1, 2, 3]), '[1, 2, 3]'); expect( - toConst([ - [1, 2], - [3, 4] - ]), - '[\n' - ' [1, 2],\n' - ' [3, 4],\n' - ']'); + toConst([ + [1, 2], + [3, 4], + ]), + '[\n' + ' [1, 2],\n' + ' [3, 4],\n' + ']', + ); }); test('writeJsonConst map examples', () { expect(toConst({}), '{}'); expect(toConst({'a': 1, 'b': 2}), "{'a': 1, 'b': 2}"); expect( - toConst({ - 'a': {'x': 1}, - 'b': {'x': 2} - }), - '{\n' - " 'a': {'x': 1},\n" - " 'b': {'x': 2},\n" - '}'); + toConst({ + 'a': {'x': 1}, + 'b': {'x': 2}, + }), + '{\n' + " 'a': {'x': 1},\n" + " 'b': {'x': 2},\n" + '}', + ); }); } diff --git a/protoc_plugin/test/constructor_args_test.dart b/protoc_plugin/test/constructor_args_test.dart index 3ad866e2f..b5859d99c 100644 --- a/protoc_plugin/test/constructor_args_test.dart +++ b/protoc_plugin/test/constructor_args_test.dart @@ -16,7 +16,7 @@ void main() { stringToInt32Field: [ MapEntry('a', 1), MapEntry('b', 2), - MapEntry('a', 3) + MapEntry('a', 3), ], int32ToStringField: {1: 'hi'}.entries, ); @@ -70,20 +70,20 @@ void main() { repeatedBytes: ['216'.codeUnits, '316'.codeUnits], repeatedGroup: [ TestAllTypes_RepeatedGroup(a: 217), - TestAllTypes_RepeatedGroup(a: 317) + TestAllTypes_RepeatedGroup(a: 317), ], repeatedNestedMessage: [ TestAllTypes_NestedMessage(bb: 218), - TestAllTypes_NestedMessage(bb: 318) + TestAllTypes_NestedMessage(bb: 318), ], repeatedForeignMessage: [ ForeignMessage(c: 219), - ForeignMessage(c: 319) + ForeignMessage(c: 319), ], repeatedImportMessage: [ImportMessage(d: 220), ImportMessage(d: 320)], repeatedNestedEnum: [ TestAllTypes_NestedEnum.BAR, - TestAllTypes_NestedEnum.BAZ + TestAllTypes_NestedEnum.BAZ, ], repeatedForeignEnum: [ForeignEnum.FOREIGN_BAR, ForeignEnum.FOREIGN_BAZ], repeatedImportEnum: [ImportEnum.IMPORT_BAR, ImportEnum.IMPORT_BAZ], diff --git a/protoc_plugin/test/descriptor_test.dart b/protoc_plugin/test/descriptor_test.dart index 31b7d6ed0..df60d98d3 100644 --- a/protoc_plugin/test/descriptor_test.dart +++ b/protoc_plugin/test/descriptor_test.dart @@ -20,8 +20,11 @@ void main() { test('Can decode enum descriptor', () { final descriptor = EnumDescriptorProto.fromBuffer(foreignEnumDescriptor); expect(descriptor.name, 'ForeignEnum'); - expect(descriptor.value.map((v) => v.name), - ['FOREIGN_FOO', 'FOREIGN_BAR', 'FOREIGN_BAZ']); + expect(descriptor.value.map((v) => v.name), [ + 'FOREIGN_FOO', + 'FOREIGN_BAR', + 'FOREIGN_BAZ', + ]); }); test('Can decode service descriptor', () { final descriptor = ServiceDescriptorProto.fromBuffer(testServiceDescriptor); @@ -30,8 +33,10 @@ void main() { }); test('Can read custom options', () { final registry = ExtensionRegistry()..add(Custom_option.myOption); - final descriptor = - DescriptorProto.fromBuffer(myMessageDescriptor, registry); + final descriptor = DescriptorProto.fromBuffer( + myMessageDescriptor, + registry, + ); final option = descriptor.options.getExtension(Custom_option.myOption); expect(option, 'Hello world!'); }); diff --git a/protoc_plugin/test/duration_test.dart b/protoc_plugin/test/duration_test.dart index 93c9d90b7..bb582ab8d 100644 --- a/protoc_plugin/test/duration_test.dart +++ b/protoc_plugin/test/duration_test.dart @@ -38,9 +38,10 @@ void main() { }); test('proto duration -> core duration -> proto duration', () { - final protoDuration = pb.Duration() - ..seconds = Int64(987654321) - ..nanos = 999999000; + final protoDuration = + pb.Duration() + ..seconds = Int64(987654321) + ..nanos = 999999000; expect(pb.Duration.fromDart(protoDuration.toDart()), protoDuration); }); diff --git a/protoc_plugin/test/enum_generator_test.dart b/protoc_plugin/test/enum_generator_test.dart index 26a1d707a..67751e2a8 100644 --- a/protoc_plugin/test/enum_generator_test.dart +++ b/protoc_plugin/test/enum_generator_test.dart @@ -12,22 +12,23 @@ import 'src/golden_file.dart'; void main() { test('testEnumGenerator', () { - final ed = EnumDescriptorProto() - ..name = 'PhoneType' - ..value.addAll([ - EnumValueDescriptorProto() - ..name = 'MOBILE' - ..number = 0, - EnumValueDescriptorProto() - ..name = 'HOME' - ..number = 1, - EnumValueDescriptorProto() - ..name = 'WORK' - ..number = 2, - EnumValueDescriptorProto() - ..name = 'BUSINESS' - ..number = 2 - ]); + final ed = + EnumDescriptorProto() + ..name = 'PhoneType' + ..value.addAll([ + EnumValueDescriptorProto() + ..name = 'MOBILE' + ..number = 0, + EnumValueDescriptorProto() + ..name = 'HOME' + ..number = 1, + EnumValueDescriptorProto() + ..name = 'WORK' + ..number = 2, + EnumValueDescriptorProto() + ..name = 'BUSINESS' + ..number = 2, + ]); final writer = IndentingWriter(filename: 'sample.proto'); final fg = FileGenerator(FileDescriptorProto(), GenerationOptions()); final eg = EnumGenerator.topLevel(ed, fg, {}, 0); diff --git a/protoc_plugin/test/extension_generator_test.dart b/protoc_plugin/test/extension_generator_test.dart index a87083b1a..35bcfe0de 100644 --- a/protoc_plugin/test/extension_generator_test.dart +++ b/protoc_plugin/test/extension_generator_test.dart @@ -15,23 +15,28 @@ import 'src/golden_file.dart'; void main() { test('testExtensionGenerator', () { - final extensionFieldDescriptor = pb.FieldDescriptorProto() - ..name = 'client_info' - ..jsonName = 'clientInfo' - ..number = 261486461 - ..label = pb.FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = pb.FieldDescriptorProto_Type.TYPE_STRING - ..extendee = '.Card'; - final messageDescriptor = pb.DescriptorProto() - ..name = 'Card' - ..extension.add(extensionFieldDescriptor); - final fileDescriptor = pb.FileDescriptorProto() - ..messageType.add(messageDescriptor) - ..extension.add(extensionFieldDescriptor); + final extensionFieldDescriptor = + pb.FieldDescriptorProto() + ..name = 'client_info' + ..jsonName = 'clientInfo' + ..number = 261486461 + ..label = pb.FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = pb.FieldDescriptorProto_Type.TYPE_STRING + ..extendee = '.Card'; + final messageDescriptor = + pb.DescriptorProto() + ..name = 'Card' + ..extension.add(extensionFieldDescriptor); + final fileDescriptor = + pb.FileDescriptorProto() + ..messageType.add(messageDescriptor) + ..extension.add(extensionFieldDescriptor); final fileGenerator = FileGenerator(fileDescriptor, GenerationOptions()); final options = parseGenerationOptions( - pb.CodeGeneratorRequest(), pb.CodeGeneratorResponse()); + pb.CodeGeneratorRequest(), + pb.CodeGeneratorResponse(), + ); link(options, [fileGenerator]); final writer = IndentingWriter(filename: 'sample.proto'); fileGenerator.extensionGenerators.single.generate(writer); @@ -47,6 +52,8 @@ class Card { expectGolden(actual, 'extension.pb.dart'); expectGolden( - writer.sourceLocationInfo.toString(), 'extension.pb.dart.meta'); + writer.sourceLocationInfo.toString(), + 'extension.pb.dart.meta', + ); }); } diff --git a/protoc_plugin/test/extension_test.dart b/protoc_plugin/test/extension_test.dart index b5ac0b64e..0e4864c17 100644 --- a/protoc_plugin/test/extension_test.dart +++ b/protoc_plugin/test/extension_test.dart @@ -14,23 +14,31 @@ import 'gen/nested_extension.pb.dart'; import 'gen/non_nested_extension.pb.dart'; import 'src/test_util.dart'; -Matcher throwsArgError(String expectedMessage) => - throwsA(predicate((dynamic x) { - expect(x, isArgumentError); - expect(x.message, expectedMessage); - return true; - })); - -final withExtensions = TestAllExtensions() - ..setExtension( - Unittest.optionalForeignMessageExtension, ForeignMessage()..c = 3) - ..setExtension(Unittest.defaultStringExtension, 'bar') - ..getExtension(Unittest.repeatedBytesExtension).add('pop'.codeUnits) - ..setExtension( - Extend_unittest.outer, - Outer() - ..inner = (Inner()..value = 'abc') - ..setExtension(Extend_unittest.extensionInner, Inner()..value = 'def')); +Matcher throwsArgError(String expectedMessage) => throwsA( + predicate((dynamic x) { + expect(x, isArgumentError); + expect(x.message, expectedMessage); + return true; + }), +); + +final withExtensions = + TestAllExtensions() + ..setExtension( + Unittest.optionalForeignMessageExtension, + ForeignMessage()..c = 3, + ) + ..setExtension(Unittest.defaultStringExtension, 'bar') + ..getExtension(Unittest.repeatedBytesExtension).add('pop'.codeUnits) + ..setExtension( + Extend_unittest.outer, + Outer() + ..inner = (Inner()..value = 'abc') + ..setExtension( + Extend_unittest.extensionInner, + Inner()..value = 'def', + ), + ); void main() { test('can set all extension types', () { @@ -86,16 +94,23 @@ void main() { test('can merge extension', () { final nestedMessage = TestAllTypes_NestedMessage()..i = 42; - final mergeSource = TestAllExtensions() - ..setExtension(Unittest.optionalNestedMessageExtension, nestedMessage); + final mergeSource = + TestAllExtensions()..setExtension( + Unittest.optionalNestedMessageExtension, + nestedMessage, + ); final nestedMessage2 = TestAllTypes_NestedMessage()..bb = 43; - final mergeDest = TestAllExtensions() - ..setExtension(Unittest.optionalNestedMessageExtension, nestedMessage2); + final mergeDest = + TestAllExtensions()..setExtension( + Unittest.optionalNestedMessageExtension, + nestedMessage2, + ); - final result = TestAllExtensions() - ..mergeFromMessage(mergeSource) - ..mergeFromMessage(mergeDest); + final result = + TestAllExtensions() + ..mergeFromMessage(mergeSource) + ..mergeFromMessage(mergeDest); expect(result.getExtension(Unittest.optionalNestedMessageExtension).i, 42); expect(result.getExtension(Unittest.optionalNestedMessageExtension).bb, 43); @@ -103,54 +118,71 @@ void main() { test("throws if field number isn't allowed for extension", () { final message = TestAllTypes(); // does not allow extensions - expect(() { - message.setExtension(Unittest.optionalInt32Extension, 0); - }, - throwsArgError( - 'Extension optionalInt32Extension not legal for message protobuf_unittest.TestAllTypes')); + expect( + () { + message.setExtension(Unittest.optionalInt32Extension, 0); + }, + throwsArgError( + 'Extension optionalInt32Extension not legal for message protobuf_unittest.TestAllTypes', + ), + ); - expect(() { - message.getExtension(Unittest.optionalInt32Extension); - }, - throwsArgError( - 'Extension optionalInt32Extension not legal for message protobuf_unittest.TestAllTypes')); + expect( + () { + message.getExtension(Unittest.optionalInt32Extension); + }, + throwsArgError( + 'Extension optionalInt32Extension not legal for message protobuf_unittest.TestAllTypes', + ), + ); }); test('throws if an int32 extension is set to a bad value', () { final message = TestAllExtensions(); - expect(() { - message.setExtension(Unittest.optionalInt32Extension, 'hello'); - }, - throwsArgError( - 'Illegal to set field optionalInt32Extension (1) of protobuf_unittest.TestAllExtensions' - ' to value (hello): not type int')); + expect( + () { + message.setExtension(Unittest.optionalInt32Extension, 'hello'); + }, + throwsArgError( + 'Illegal to set field optionalInt32Extension (1) of protobuf_unittest.TestAllExtensions' + ' to value (hello): not type int', + ), + ); }); test('throws if an int64 extension is set to a bad value', () { final message = TestAllExtensions(); - expect(() { - message.setExtension(Unittest.optionalInt64Extension, 123); - }, - throwsArgError( - 'Illegal to set field optionalInt64Extension (2) of protobuf_unittest.TestAllExtensions' - ' to value (123): not Int64')); + expect( + () { + message.setExtension(Unittest.optionalInt64Extension, 123); + }, + throwsArgError( + 'Illegal to set field optionalInt64Extension (2) of protobuf_unittest.TestAllExtensions' + ' to value (123): not Int64', + ), + ); }); test('throws if a message extension is set to a bad value', () { final message = TestAllExtensions(); // For a non-repeated message, we only check for a GeneratedMessage. - expect(() { - message.setExtension(Unittest.optionalNestedMessageExtension, 123); - }, - throwsArgError( - 'Illegal to set field optionalNestedMessageExtension (18)' - ' of protobuf_unittest.TestAllExtensions to value (123): not a GeneratedMessage')); + expect( + () { + message.setExtension(Unittest.optionalNestedMessageExtension, 123); + }, + throwsArgError( + 'Illegal to set field optionalNestedMessageExtension (18)' + ' of protobuf_unittest.TestAllExtensions to value (123): not a GeneratedMessage', + ), + ); // For a repeated message, the type check is exact. expect(() { message.addExtension( - Unittest.repeatedNestedMessageExtension, TestAllTypes()); + Unittest.repeatedNestedMessageExtension, + TestAllTypes(), + ); }, throwsATypeError); }); @@ -158,30 +190,39 @@ void main() { final message = TestAllExtensions(); // For a non-repeated enum, we only check for a ProtobufEnum. - expect(() { - message.setExtension(Unittest.optionalNestedEnumExtension, 123); - }, - throwsArgError('Illegal to set field optionalNestedEnumExtension (21)' - ' of protobuf_unittest.TestAllExtensions to value (123): not type ProtobufEnum')); + expect( + () { + message.setExtension(Unittest.optionalNestedEnumExtension, 123); + }, + throwsArgError( + 'Illegal to set field optionalNestedEnumExtension (21)' + ' of protobuf_unittest.TestAllExtensions to value (123): not type ProtobufEnum', + ), + ); // For a repeated enum, the type check is exact. expect(() { message.addExtension( - Unittest.repeatedForeignEnumExtension, TestAllTypes_NestedEnum.FOO); + Unittest.repeatedForeignEnumExtension, + TestAllTypes_NestedEnum.FOO, + ); }, throwsATypeError); }); test('can extend a message with a message field with a different type', () { - expect(Non_nested_extension.nonNestedExtension.makeDefault!(), - TypeMatcher()); + expect( + Non_nested_extension.nonNestedExtension.makeDefault!(), + TypeMatcher(), + ); expect(Non_nested_extension.nonNestedExtension.name, 'nonNestedExtension'); }); test('can extend a message with a message field of the same type', () { expect( - MyNestedExtension.recursiveExtension.makeDefault!() - is MessageToBeExtended, - isTrue); + MyNestedExtension.recursiveExtension.makeDefault!() + is MessageToBeExtended, + isTrue, + ); expect(MyNestedExtension.recursiveExtension.name, 'recursiveExtension'); }); @@ -199,16 +240,22 @@ void main() { }); test('to toDebugString', () { - final value = TestAllExtensions() - ..setExtension(Unittest.optionalInt32Extension, 1) - ..addExtension(Unittest.repeatedStringExtension, 'hello') - ..addExtension(Unittest.repeatedStringExtension, 'world') - ..setExtension(Unittest.optionalNestedMessageExtension, - TestAllTypes_NestedMessage()..i = 42) - ..setExtension( - Unittest.optionalNestedEnumExtension, TestAllTypes_NestedEnum.BAR); - - final expected = '[optionalInt32Extension]: 1\n' + final value = + TestAllExtensions() + ..setExtension(Unittest.optionalInt32Extension, 1) + ..addExtension(Unittest.repeatedStringExtension, 'hello') + ..addExtension(Unittest.repeatedStringExtension, 'world') + ..setExtension( + Unittest.optionalNestedMessageExtension, + TestAllTypes_NestedMessage()..i = 42, + ) + ..setExtension( + Unittest.optionalNestedEnumExtension, + TestAllTypes_NestedEnum.BAR, + ); + + final expected = + '[optionalInt32Extension]: 1\n' '[optionalNestedMessageExtension]: {\n' ' i: 42\n' '}\n' @@ -220,9 +267,10 @@ void main() { }); test('can compare messages with and without extensions', () { - final withExtension = TestFieldOrderings() - ..myString = 'foo' - ..setExtension(Unittest.myExtensionString, 'bar'); + final withExtension = + TestFieldOrderings() + ..myString = 'foo' + ..setExtension(Unittest.myExtensionString, 'bar'); final b = withExtension.writeToBuffer(); final withUnknownField = TestFieldOrderings.fromBuffer(b); final r = ExtensionRegistry(); @@ -241,102 +289,122 @@ void main() { }); test( - 'ExtensionRegistry.reparseMessage will preserve already registered extensions', - () { - final r1 = ExtensionRegistry(); - Unittest.registerAllExtensions(r1); - - final r2 = ExtensionRegistry(); - Extend_unittest.registerAllExtensions(r2); - final withUnknownFields = - TestAllExtensions.fromBuffer(withExtensions.writeToBuffer()); - final reparsedR1 = r1.reparseMessage(withUnknownFields); - - expect( - reparsedR1.getExtension(Unittest.optionalForeignMessageExtension).c, 3); - - expect( + 'ExtensionRegistry.reparseMessage will preserve already registered extensions', + () { + final r1 = ExtensionRegistry(); + Unittest.registerAllExtensions(r1); + + final r2 = ExtensionRegistry(); + Extend_unittest.registerAllExtensions(r2); + final withUnknownFields = TestAllExtensions.fromBuffer( + withExtensions.writeToBuffer(), + ); + final reparsedR1 = r1.reparseMessage(withUnknownFields); + + expect( + reparsedR1.getExtension(Unittest.optionalForeignMessageExtension).c, + 3, + ); + + expect( r2 .reparseMessage(reparsedR1) .getExtension(Unittest.optionalForeignMessageExtension) .c, - 3); - }); + 3, + ); + }, + ); test( - 'ExtensionRegistry.reparseMessage reparses extensions that were not in the original registry', - () { - final r = ExtensionRegistry(); - Unittest.registerAllExtensions(r); - Extend_unittest.registerAllExtensions(r); - - final withUnknownFields = - TestAllExtensions.fromBuffer(withExtensions.writeToBuffer()); - final reparsed = r.reparseMessage(withUnknownFields); - - expect( + 'ExtensionRegistry.reparseMessage reparses extensions that were not in the original registry', + () { + final r = ExtensionRegistry(); + Unittest.registerAllExtensions(r); + Extend_unittest.registerAllExtensions(r); + + final withUnknownFields = TestAllExtensions.fromBuffer( + withExtensions.writeToBuffer(), + ); + final reparsed = r.reparseMessage(withUnknownFields); + + expect( () => withUnknownFields.getExtension(Unittest.defaultStringExtension), - throwsA(const TypeMatcher())); + throwsA(const TypeMatcher()), + ); - expect(reparsed.getExtension(Unittest.defaultStringExtension), 'bar'); + expect(reparsed.getExtension(Unittest.defaultStringExtension), 'bar'); - expect( - reparsed.unknownFields - .getField(Unittest.defaultStringExtension.tagNumber), + expect( + reparsed.unknownFields.getField( + Unittest.defaultStringExtension.tagNumber, + ), null, reason: - 'ExtensionRegistry.reparseMessage does not leave reparsed fields in unknownFields'); - expect(reparsed.getExtension(Unittest.repeatedBytesExtension), - ['pop'.codeUnits]); + 'ExtensionRegistry.reparseMessage does not leave reparsed fields in unknownFields', + ); + expect(reparsed.getExtension(Unittest.repeatedBytesExtension), [ + 'pop'.codeUnits, + ]); - expect( - reparsed.getExtension(Unittest.optionalForeignMessageExtension).c, 3); + expect( + reparsed.getExtension(Unittest.optionalForeignMessageExtension).c, + 3, + ); - expect(reparsed.getExtension(Extend_unittest.outer).inner.value, 'abc'); + expect(reparsed.getExtension(Extend_unittest.outer).inner.value, 'abc'); - final onlyOuter = ExtensionRegistry()..add(Extend_unittest.outer); - final onlyOuterReparsed = onlyOuter.reparseMessage(withUnknownFields); - expect( + final onlyOuter = ExtensionRegistry()..add(Extend_unittest.outer); + final onlyOuterReparsed = onlyOuter.reparseMessage(withUnknownFields); + expect( onlyOuterReparsed .getExtension(Extend_unittest.outer) .hasExtension(Extend_unittest.extensionInner), - isFalse); - expect( + isFalse, + ); + expect( () => onlyOuter .reparseMessage(withUnknownFields) .getExtension(Extend_unittest.outer) .getExtension(Extend_unittest.extensionInner), - throwsA(const TypeMatcher())); + throwsA(const TypeMatcher()), + ); - expect( + expect( reparsed .getExtension(Extend_unittest.outer) .hasExtension(Extend_unittest.extensionInner), - isTrue); - expect( + isTrue, + ); + expect( reparsed .getExtension(Extend_unittest.outer) .getExtension(Extend_unittest.extensionInner) .value, - 'def'); - }); + 'def', + ); + }, + ); test('ExtensionRegistry.reparseMessage does not update the original', () { final r = ExtensionRegistry(); Unittest.registerAllExtensions(r); Extend_unittest.registerAllExtensions(r); - final withUnknownFields = - TestAllExtensions.fromBuffer(withExtensions.writeToBuffer()); + final withUnknownFields = TestAllExtensions.fromBuffer( + withExtensions.writeToBuffer(), + ); - final reparsedWithEmpty = - ExtensionRegistry().reparseMessage(withUnknownFields); + final reparsedWithEmpty = ExtensionRegistry().reparseMessage( + withUnknownFields, + ); expect(reparsedWithEmpty, same(withUnknownFields)); final reparsed = r.reparseMessage(withUnknownFields); - final strings = withUnknownFields - .getExtension(Unittest.repeatedStringExtension) as List; + final strings = + withUnknownFields.getExtension(Unittest.repeatedStringExtension) + as List; expect(strings, []); strings.add('pop2'); expect(reparsed.getExtension(Unittest.repeatedStringExtension), []); @@ -354,205 +422,275 @@ void main() { final withMalformedExtensionEncoding = TestAllExtensions.fromBuffer([ 154, 1, 2, 8, 3, 210, // 4, 3, 98, 97, 114, 194, 6, 14, 10, 5, 10, 4, - 97, 98, 99, 18, 5, 10, 3, 100, 101, 102 + 97, 98, 99, 18, 5, 10, 3, 100, 101, 102, ]); expect( - r - .reparseMessage(withMalformedExtensionEncoding) - .getExtension(Unittest.defaultStringExtension), - 'bar', - reason: - 'this succeeds because it does not decode Extend_unittest.outer'); - expect(() => r2.reparseMessage(withMalformedExtensionEncoding), - throwsA(const TypeMatcher())); + r + .reparseMessage(withMalformedExtensionEncoding) + .getExtension(Unittest.defaultStringExtension), + 'bar', + reason: 'this succeeds because it does not decode Extend_unittest.outer', + ); + expect( + () => r2.reparseMessage(withMalformedExtensionEncoding), + throwsA(const TypeMatcher()), + ); }); test('ExtensionRegistry.reparseMessage preserves frozenness', () { final r = ExtensionRegistry(); Unittest.registerAllExtensions(r); - final withUnknownFields = - TestAllExtensions.fromBuffer(withExtensions.writeToBuffer()); + final withUnknownFields = TestAllExtensions.fromBuffer( + withExtensions.writeToBuffer(), + ); withUnknownFields.freeze(); expect( - () => r - .reparseMessage(withUnknownFields) - .setExtension(Unittest.defaultStringExtension, 'blah'), - throwsA(TypeMatcher())); + () => r + .reparseMessage(withUnknownFields) + .setExtension(Unittest.defaultStringExtension, 'blah'), + throwsA(TypeMatcher()), + ); }); test( - 'ExtensionRegistry.reparseMessage returns the same object when no new extensions are parsed', - () { - final original = Outer() - ..inner = (Inner() - ..innerMost = (InnerMost() - ..setExtension(Extend_unittest.innerMostExtensionString, 'a'))) - ..inners.addAll([ - (Inner()..setExtension(Extend_unittest.innerExtensionString, 'a')), - Inner()..value = 'value' - ]) - ..innerMap[0] = - (Inner()..setExtension(Extend_unittest.innerExtensionString, 'a')); - - final reparsed = ExtensionRegistry().reparseMessage(original); - expect(identical(reparsed, original), isTrue); - }); + 'ExtensionRegistry.reparseMessage returns the same object when no new extensions are parsed', + () { + final original = + Outer() + ..inner = + (Inner() + ..innerMost = + (InnerMost()..setExtension( + Extend_unittest.innerMostExtensionString, + 'a', + ))) + ..inners.addAll([ + (Inner() + ..setExtension(Extend_unittest.innerExtensionString, 'a')), + Inner()..value = 'value', + ]) + ..innerMap[0] = + (Inner() + ..setExtension(Extend_unittest.innerExtensionString, 'a')); + + final reparsed = ExtensionRegistry().reparseMessage(original); + expect(identical(reparsed, original), isTrue); + }, + ); test( - 'ExtensionRegistry.reparseMessage reparses extension in deeply nested subfield', - () { - final original = Outer() - ..inner = (Inner() - ..innerMost = (InnerMost() - ..setExtension(Extend_unittest.innerMostExtensionString, 'a'))); - - final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); - - expect( - withUnknownFields.inner.innerMost - .hasExtension(Extend_unittest.innerMostExtensionString), - isFalse); - - final r = ExtensionRegistry() - ..add(Extend_unittest.innerMostExtensionString); - final reparsed = r.reparseMessage(withUnknownFields); - - expect(identical(reparsed.inner, withUnknownFields.inner), isFalse); - expect( + 'ExtensionRegistry.reparseMessage reparses extension in deeply nested subfield', + () { + final original = + Outer() + ..inner = + (Inner() + ..innerMost = + (InnerMost()..setExtension( + Extend_unittest.innerMostExtensionString, + 'a', + ))); + + final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); + + expect( + withUnknownFields.inner.innerMost.hasExtension( + Extend_unittest.innerMostExtensionString, + ), + isFalse, + ); + + final r = + ExtensionRegistry()..add(Extend_unittest.innerMostExtensionString); + final reparsed = r.reparseMessage(withUnknownFields); + + expect(identical(reparsed.inner, withUnknownFields.inner), isFalse); + expect( identical(reparsed.inner.innerMost, withUnknownFields.inner.innerMost), - isFalse); - expect( - reparsed.inner.innerMost - .hasExtension(Extend_unittest.innerMostExtensionString), - isTrue); - }); + isFalse, + ); + expect( + reparsed.inner.innerMost.hasExtension( + Extend_unittest.innerMostExtensionString, + ), + isTrue, + ); + }, + ); test( - 'ExtensionRegistry.reparseMessage reparses extensions in all nested subfields', - () { - final original = Outer() - ..inner = (Inner() - ..setExtension(Extend_unittest.innerExtensionString, 'a') - ..innerMost = (InnerMost() - ..setExtension(Extend_unittest.innerMostExtensionString, 'a'))); - - final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); - - expect( - withUnknownFields.inner - .hasExtension(Extend_unittest.innerExtensionString), - isFalse); - expect( - withUnknownFields.inner.innerMost - .hasExtension(Extend_unittest.innerMostExtensionString), - isFalse); - - final r = ExtensionRegistry() - ..addAll([ - Extend_unittest.innerExtensionString, - Extend_unittest.innerMostExtensionString - ]); - final reparsed = r.reparseMessage(withUnknownFields); - - expect(identical(reparsed.inner, withUnknownFields.inner), isFalse); - expect( + 'ExtensionRegistry.reparseMessage reparses extensions in all nested subfields', + () { + final original = + Outer() + ..inner = + (Inner() + ..setExtension(Extend_unittest.innerExtensionString, 'a') + ..innerMost = + (InnerMost()..setExtension( + Extend_unittest.innerMostExtensionString, + 'a', + ))); + + final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); + + expect( + withUnknownFields.inner.hasExtension( + Extend_unittest.innerExtensionString, + ), + isFalse, + ); + expect( + withUnknownFields.inner.innerMost.hasExtension( + Extend_unittest.innerMostExtensionString, + ), + isFalse, + ); + + final r = + ExtensionRegistry()..addAll([ + Extend_unittest.innerExtensionString, + Extend_unittest.innerMostExtensionString, + ]); + final reparsed = r.reparseMessage(withUnknownFields); + + expect(identical(reparsed.inner, withUnknownFields.inner), isFalse); + expect( identical(reparsed.inner.innerMost, withUnknownFields.inner.innerMost), - isFalse); - expect(reparsed.inner.hasExtension(Extend_unittest.innerExtensionString), - isTrue); - expect( - reparsed.inner.innerMost - .hasExtension(Extend_unittest.innerMostExtensionString), - isTrue); - }); + isFalse, + ); + expect( + reparsed.inner.hasExtension(Extend_unittest.innerExtensionString), + isTrue, + ); + expect( + reparsed.inner.innerMost.hasExtension( + Extend_unittest.innerMostExtensionString, + ), + isTrue, + ); + }, + ); test( - 'ExtensionRegistry.reparseMessage doesn\'t copy deepest subfield without extensions', - () { - final original = Outer() - ..inner = (Inner() - ..setExtension(Extend_unittest.innerExtensionString, 'a') - ..innerMost = InnerMost()); - - final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); - - expect( - withUnknownFields.inner - .hasExtension(Extend_unittest.innerExtensionString), - false); - - final r = ExtensionRegistry()..add(Extend_unittest.innerExtensionString); - final reparsed = r.reparseMessage(withUnknownFields); - - expect(identical(reparsed.inner, withUnknownFields.inner), isFalse); - expect( + 'ExtensionRegistry.reparseMessage doesn\'t copy deepest subfield without extensions', + () { + final original = + Outer() + ..inner = + (Inner() + ..setExtension(Extend_unittest.innerExtensionString, 'a') + ..innerMost = InnerMost()); + + final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); + + expect( + withUnknownFields.inner.hasExtension( + Extend_unittest.innerExtensionString, + ), + false, + ); + + final r = ExtensionRegistry()..add(Extend_unittest.innerExtensionString); + final reparsed = r.reparseMessage(withUnknownFields); + + expect(identical(reparsed.inner, withUnknownFields.inner), isFalse); + expect( identical(reparsed.inner.innerMost, withUnknownFields.inner.innerMost), - isTrue); - expect(reparsed.inner.hasExtension(Extend_unittest.innerExtensionString), - isTrue); - }); + isTrue, + ); + expect( + reparsed.inner.hasExtension(Extend_unittest.innerExtensionString), + isTrue, + ); + }, + ); test( - 'ExtensionRegistry.reparseMessage reparses extensions in repeated fields', - () { - final original = Outer() - ..inners.addAll([ - (Inner()..setExtension(Extend_unittest.innerExtensionString, 'a')), - Inner()..value = 'value' - ]); - - final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); - - expect( - withUnknownFields.inners.first - .hasExtension(Extend_unittest.innerExtensionString), - isFalse); - - final r = ExtensionRegistry()..add(Extend_unittest.innerExtensionString); - final reparsed = r.reparseMessage(withUnknownFields); - - expect( + 'ExtensionRegistry.reparseMessage reparses extensions in repeated fields', + () { + final original = + Outer() + ..inners.addAll([ + (Inner() + ..setExtension(Extend_unittest.innerExtensionString, 'a')), + Inner()..value = 'value', + ]); + + final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); + + expect( + withUnknownFields.inners.first.hasExtension( + Extend_unittest.innerExtensionString, + ), + isFalse, + ); + + final r = ExtensionRegistry()..add(Extend_unittest.innerExtensionString); + final reparsed = r.reparseMessage(withUnknownFields); + + expect( reparsed.inners[0].hasExtension(Extend_unittest.innerExtensionString), - isTrue); - expect(identical(withUnknownFields.inners[1], reparsed.inners[1]), isTrue); - }); - - test('ExtensionRegistry.reparseMessage reparses extensions in map fields', - () { - final original = Outer() - ..innerMap[0] = - (Inner()..setExtension(Extend_unittest.innerExtensionString, 'a')) - ..innerMap[1] = (Inner()) - ..stringMap['hello'] = 'world'; - - final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); - - expect( - withUnknownFields.innerMap[0]! - .hasExtension(Extend_unittest.innerExtensionString), - isFalse); - - final r = ExtensionRegistry()..add(Extend_unittest.innerExtensionString); - final reparsed = r.reparseMessage(withUnknownFields); + isTrue, + ); + expect( + identical(withUnknownFields.inners[1], reparsed.inners[1]), + isTrue, + ); + }, + ); - expect( - reparsed.innerMap[0]! - .hasExtension(Extend_unittest.innerExtensionString), - isTrue); - expect( - identical(withUnknownFields.innerMap[1], reparsed.innerMap[1]), isTrue); - expect(withUnknownFields.stringMap.length, 1); - expect(reparsed.stringMap.length, 1); - expect(withUnknownFields.stringMap['hello']!, reparsed.stringMap['hello']!); - }); + test( + 'ExtensionRegistry.reparseMessage reparses extensions in map fields', + () { + final original = + Outer() + ..innerMap[0] = + (Inner() + ..setExtension(Extend_unittest.innerExtensionString, 'a')) + ..innerMap[1] = (Inner()) + ..stringMap['hello'] = 'world'; + + final withUnknownFields = Outer.fromBuffer(original.writeToBuffer()); + + expect( + withUnknownFields.innerMap[0]!.hasExtension( + Extend_unittest.innerExtensionString, + ), + isFalse, + ); + + final r = ExtensionRegistry()..add(Extend_unittest.innerExtensionString); + final reparsed = r.reparseMessage(withUnknownFields); + + expect( + reparsed.innerMap[0]!.hasExtension( + Extend_unittest.innerExtensionString, + ), + isTrue, + ); + expect( + identical(withUnknownFields.innerMap[1], reparsed.innerMap[1]), + isTrue, + ); + expect(withUnknownFields.stringMap.length, 1); + expect(reparsed.stringMap.length, 1); + expect( + withUnknownFields.stringMap['hello']!, + reparsed.stringMap['hello']!, + ); + }, + ); test('consistent hashcode for reparsed messages with extensions', () { final r = ExtensionRegistry()..add(Extend_unittest.outer); - final m = TestAllExtensions() - ..setExtension( - Extend_unittest.outer, Outer()..inner = (Inner()..value = 'hello')); + final m = + TestAllExtensions()..setExtension( + Extend_unittest.outer, + Outer()..inner = (Inner()..value = 'hello'), + ); final b = m.writeToBuffer(); final c = TestAllExtensions.fromBuffer(b); final d = r.reparseMessage(c); diff --git a/protoc_plugin/test/extension_unknown_interaction_test.dart b/protoc_plugin/test/extension_unknown_interaction_test.dart index eaa8b2313..e730f056e 100644 --- a/protoc_plugin/test/extension_unknown_interaction_test.dart +++ b/protoc_plugin/test/extension_unknown_interaction_test.dart @@ -10,13 +10,19 @@ import 'gen/google/protobuf/unittest.pb.dart'; void main() { test('setExtension clears unknown field with same tag number', () { final m = TestAllExtensions(); - m.unknownFields.addField(Unittest.optionalInt32Extension.tagNumber, - UnknownFieldSetField()..addFixed32(33)); - expect(m.unknownFields.hasField(Unittest.optionalInt32Extension.tagNumber), - isTrue); + m.unknownFields.addField( + Unittest.optionalInt32Extension.tagNumber, + UnknownFieldSetField()..addFixed32(33), + ); + expect( + m.unknownFields.hasField(Unittest.optionalInt32Extension.tagNumber), + isTrue, + ); m.setExtension(Unittest.optionalInt32Extension, 42); expect(m.getExtension(Unittest.optionalInt32Extension), 42); - expect(m.unknownFields.hasField(Unittest.optionalInt32Extension.tagNumber), - isFalse); + expect( + m.unknownFields.hasField(Unittest.optionalInt32Extension.tagNumber), + isFalse, + ); }); } diff --git a/protoc_plugin/test/file_generator_test.dart b/protoc_plugin/test/file_generator_test.dart index 34d9e9ab2..af88a4254 100644 --- a/protoc_plugin/test/file_generator_test.dart +++ b/protoc_plugin/test/file_generator_test.dart @@ -13,134 +13,160 @@ import 'package:test/test.dart'; import 'src/golden_file.dart'; -FileDescriptorProto buildFileDescriptor( - {bool phoneNumber = true, bool topLevelEnum = false}) { +FileDescriptorProto buildFileDescriptor({ + bool phoneNumber = true, + bool topLevelEnum = false, +}) { final fd = FileDescriptorProto()..name = 'test'; if (topLevelEnum) { - fd.enumType.add(EnumDescriptorProto() - ..name = 'PhoneType' - ..value.addAll([ - EnumValueDescriptorProto() - ..name = 'MOBILE' - ..number = 0, - EnumValueDescriptorProto() - ..name = 'HOME' - ..number = 1, - EnumValueDescriptorProto() - ..name = 'WORK' - ..number = 2, - EnumValueDescriptorProto() - ..name = 'BUSINESS' - ..number = 2 - ])); + fd.enumType.add( + EnumDescriptorProto() + ..name = 'PhoneType' + ..value.addAll([ + EnumValueDescriptorProto() + ..name = 'MOBILE' + ..number = 0, + EnumValueDescriptorProto() + ..name = 'HOME' + ..number = 1, + EnumValueDescriptorProto() + ..name = 'WORK' + ..number = 2, + EnumValueDescriptorProto() + ..name = 'BUSINESS' + ..number = 2, + ]), + ); } if (phoneNumber) { - fd.messageType.add(DescriptorProto() - ..name = 'PhoneNumber' - ..field.addAll([ - // required string number = 1; - FieldDescriptorProto() - ..name = 'number' - ..jsonName = 'number' - ..number = 1 - ..label = FieldDescriptorProto_Label.LABEL_REQUIRED - ..type = FieldDescriptorProto_Type.TYPE_STRING, - // optional int32 type = 2; - // OR - // optional PhoneType type = 2; - FieldDescriptorProto() - ..name = 'type' - ..jsonName = 'type' - ..number = 2 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = topLevelEnum - ? FieldDescriptorProto_Type.TYPE_ENUM - : FieldDescriptorProto_Type.TYPE_INT32 - ..typeName = topLevelEnum ? '.PhoneType' : '', - // optional string name = 3 [default = "$"]; - FieldDescriptorProto() - ..name = 'name' - ..jsonName = 'name' - ..number = 3 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_STRING - ..defaultValue = r'$' - ])); + fd.messageType.add( + DescriptorProto() + ..name = 'PhoneNumber' + ..field.addAll([ + // required string number = 1; + FieldDescriptorProto() + ..name = 'number' + ..jsonName = 'number' + ..number = 1 + ..label = FieldDescriptorProto_Label.LABEL_REQUIRED + ..type = FieldDescriptorProto_Type.TYPE_STRING, + // optional int32 type = 2; + // OR + // optional PhoneType type = 2; + FieldDescriptorProto() + ..name = 'type' + ..jsonName = 'type' + ..number = 2 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = + topLevelEnum + ? FieldDescriptorProto_Type.TYPE_ENUM + : FieldDescriptorProto_Type.TYPE_INT32 + ..typeName = topLevelEnum ? '.PhoneType' : '', + // optional string name = 3 [default = "$"]; + FieldDescriptorProto() + ..name = 'name' + ..jsonName = 'name' + ..number = 3 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_STRING + ..defaultValue = r'$', + ]), + ); } return fd; } FileDescriptorProto createInt64Proto() { final fd = FileDescriptorProto()..name = 'test'; - fd.messageType.add(DescriptorProto() - ..name = 'Int64' - ..field.add( - // optional int64 value = 1; - FieldDescriptorProto() - ..name = 'value' - ..jsonName = 'value' - ..number = 1 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_INT64, - )); + fd.messageType.add( + DescriptorProto() + ..name = 'Int64' + ..field.add( + // optional int64 value = 1; + FieldDescriptorProto() + ..name = 'value' + ..jsonName = 'value' + ..number = 1 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_INT64, + ), + ); return fd; } void main() { - test('FileGenerator outputs a .pb.dart file for a proto with one message', - () { - final fd = buildFileDescriptor(); - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; - final fg = FileGenerator(fd, options); - link(options, [fg]); - expectGolden(fg.generateMainFile().toString(), 'oneMessage.pb.dart'); - }); + test( + 'FileGenerator outputs a .pb.dart file for a proto with one message', + () { + final fd = buildFileDescriptor(); + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; + final fg = FileGenerator(fd, options); + link(options, [fg]); + expectGolden(fg.generateMainFile().toString(), 'oneMessage.pb.dart'); + }, + ); test('FileGenerator outputs a .pb.dart file for an Int64 message', () { final fd = createInt64Proto(); - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); link(options, [fg]); expectGolden(fg.generateMainFile().toString(), 'int64.pb.dart'); }); test( - 'FileGenerator outputs a .pb.dart.meta file for a proto with one message', - () { - final fd = buildFileDescriptor(); - final options = parseGenerationOptions( - CodeGeneratorRequest() - ..parameter = 'generate_kythe_info,disable_constructor_args', - CodeGeneratorResponse())!; - final fg = FileGenerator(fd, options); - link(options, [fg]); - expectGolden(fg.generateMainFile().sourceLocationInfo.toString(), - 'oneMessage.pb.dart.meta'); - }); + 'FileGenerator outputs a .pb.dart.meta file for a proto with one message', + () { + final fd = buildFileDescriptor(); + final options = + parseGenerationOptions( + CodeGeneratorRequest() + ..parameter = 'generate_kythe_info,disable_constructor_args', + CodeGeneratorResponse(), + )!; + final fg = FileGenerator(fd, options); + link(options, [fg]); + expectGolden( + fg.generateMainFile().sourceLocationInfo.toString(), + 'oneMessage.pb.dart.meta', + ); + }, + ); - test('FileGenerator outputs a pbjson.dart file for a proto with one message', - () { - final fd = buildFileDescriptor(); - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; - final fg = FileGenerator(fd, options); - link(options, [fg]); - expectGolden(fg.generateJsonFile(), 'oneMessage.pbjson.dart'); - }); + test( + 'FileGenerator outputs a pbjson.dart file for a proto with one message', + () { + final fd = buildFileDescriptor(); + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; + final fg = FileGenerator(fd, options); + link(options, [fg]); + expectGolden(fg.generateJsonFile(), 'oneMessage.pbjson.dart'); + }, + ); test('FileGenerator generates files for a top-level enum', () { final fd = buildFileDescriptor(phoneNumber: false, topLevelEnum: true); - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); link(options, [fg]); @@ -150,24 +176,32 @@ void main() { test('FileGenerator generates metadata files for a top-level enum', () { final fd = buildFileDescriptor(phoneNumber: false, topLevelEnum: true); - final options = parseGenerationOptions( - CodeGeneratorRequest() - ..parameter = 'generate_kythe_info,disable_constructor_args', - CodeGeneratorResponse())!; + final options = + parseGenerationOptions( + CodeGeneratorRequest() + ..parameter = 'generate_kythe_info,disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); link(options, [fg]); - expectGolden(fg.generateMainFile().sourceLocationInfo.toString(), - 'topLevelEnum.pb.dart.meta'); - expectGolden(fg.generateEnumFile().sourceLocationInfo.toString(), - 'topLevelEnum.pbenum.dart.meta'); + expectGolden( + fg.generateMainFile().sourceLocationInfo.toString(), + 'topLevelEnum.pb.dart.meta', + ); + expectGolden( + fg.generateEnumFile().sourceLocationInfo.toString(), + 'topLevelEnum.pbenum.dart.meta', + ); }); test('FileGenerator generates a .pbjson.dart file for a top-level enum', () { final fd = buildFileDescriptor(phoneNumber: false, topLevelEnum: true); - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); link(options, [fg]); @@ -177,9 +211,11 @@ void main() { test('FileGenerator outputs library for a .proto in a package', () { final fd = buildFileDescriptor(); fd.package = 'pb_library'; - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); link(options, [fg]); @@ -190,21 +226,26 @@ void main() { }); test('FileGenerator outputs a fixnum import when needed', () { - final fd = FileDescriptorProto() - ..name = 'test' - ..messageType.add(DescriptorProto() - ..name = 'Count' - ..field.addAll([ - FieldDescriptorProto() - ..name = 'count' - ..jsonName = 'count' - ..number = 1 - ..type = FieldDescriptorProto_Type.TYPE_INT64 - ])); - - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; + final fd = + FileDescriptorProto() + ..name = 'test' + ..messageType.add( + DescriptorProto() + ..name = 'Count' + ..field.addAll([ + FieldDescriptorProto() + ..name = 'count' + ..jsonName = 'count' + ..number = 1 + ..type = FieldDescriptorProto_Type.TYPE_INT64, + ]), + ); + + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); link(options, [fg]); @@ -217,21 +258,27 @@ void main() { test('FileGenerator outputs files for a service', () { final empty = DescriptorProto()..name = 'Empty'; - final sd = ServiceDescriptorProto() - ..name = 'Test' - ..method.add(MethodDescriptorProto() - ..name = 'Ping' - ..inputType = '.Empty' - ..outputType = '.Empty'); - - final fd = FileDescriptorProto() - ..name = 'test' - ..messageType.add(empty) - ..service.add(sd); - - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; + final sd = + ServiceDescriptorProto() + ..name = 'Test' + ..method.add( + MethodDescriptorProto() + ..name = 'Ping' + ..inputType = '.Empty' + ..outputType = '.Empty', + ); + + final fd = + FileDescriptorProto() + ..name = 'test' + ..messageType.add(empty) + ..service.add(sd); + + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); link(options, [fg]); @@ -242,81 +289,93 @@ void main() { expectGolden(fg.generateServerFile(), 'service.pbserver.dart'); }); - test('FileGenerator does not output legacy service stubs if gRPC is selected', - () { - final empty = DescriptorProto()..name = 'Empty'; - - final sd = ServiceDescriptorProto() - ..name = 'Test' - ..method.add(MethodDescriptorProto() - ..name = 'Ping' - ..inputType = '.Empty' - ..outputType = '.Empty'); - - final fd = FileDescriptorProto() - ..name = 'test' - ..messageType.add(empty) - ..service.add(sd); - - final options = GenerationOptions(useGrpc: true); - - final fg = FileGenerator(fd, options); - link(options, [fg]); - - final writer = IndentingWriter(filename: ''); - fg.writeMainHeader(writer); - expectGolden(fg.generateMainFile().toString(), 'grpc_service.pb.dart'); - }); + test( + 'FileGenerator does not output legacy service stubs if gRPC is selected', + () { + final empty = DescriptorProto()..name = 'Empty'; + + final sd = + ServiceDescriptorProto() + ..name = 'Test' + ..method.add( + MethodDescriptorProto() + ..name = 'Ping' + ..inputType = '.Empty' + ..outputType = '.Empty', + ); + + final fd = + FileDescriptorProto() + ..name = 'test' + ..messageType.add(empty) + ..service.add(sd); + + final options = GenerationOptions(useGrpc: true); + + final fg = FileGenerator(fd, options); + link(options, [fg]); + + final writer = IndentingWriter(filename: ''); + fg.writeMainHeader(writer); + expectGolden(fg.generateMainFile().toString(), 'grpc_service.pb.dart'); + }, + ); test('FileGenerator outputs gRPC stubs if gRPC is selected', () { final input = DescriptorProto()..name = 'Input'; final output = DescriptorProto()..name = 'Output'; - final unary = MethodDescriptorProto() - ..name = 'Unary' - ..inputType = '.Input' - ..outputType = '.Output' - ..clientStreaming = false - ..serverStreaming = false; - - final clientStreaming = MethodDescriptorProto() - ..name = 'ClientStreaming' - ..inputType = '.Input' - ..outputType = '.Output' - ..clientStreaming = true - ..serverStreaming = false; - - final serverStreaming = MethodDescriptorProto() - ..name = 'ServerStreaming' - ..inputType = '.Input' - ..outputType = '.Output' - ..clientStreaming = false - ..serverStreaming = true; - - final bidirectional = MethodDescriptorProto() - ..name = 'Bidirectional' - ..inputType = '.Input' - ..outputType = '.Output' - ..clientStreaming = true - ..serverStreaming = true; + final unary = + MethodDescriptorProto() + ..name = 'Unary' + ..inputType = '.Input' + ..outputType = '.Output' + ..clientStreaming = false + ..serverStreaming = false; + + final clientStreaming = + MethodDescriptorProto() + ..name = 'ClientStreaming' + ..inputType = '.Input' + ..outputType = '.Output' + ..clientStreaming = true + ..serverStreaming = false; + + final serverStreaming = + MethodDescriptorProto() + ..name = 'ServerStreaming' + ..inputType = '.Input' + ..outputType = '.Output' + ..clientStreaming = false + ..serverStreaming = true; + + final bidirectional = + MethodDescriptorProto() + ..name = 'Bidirectional' + ..inputType = '.Input' + ..outputType = '.Output' + ..clientStreaming = true + ..serverStreaming = true; // A method with name 'call' to test that it doesn't conflict with the // method arguments with the same name, see issue #963. - final keywordCall = MethodDescriptorProto() - ..name = 'Call' - ..inputType = '.Input' - ..outputType = '.Output' - ..clientStreaming = false - ..serverStreaming = false; + final keywordCall = + MethodDescriptorProto() + ..name = 'Call' + ..inputType = '.Input' + ..outputType = '.Output' + ..clientStreaming = false + ..serverStreaming = false; // A method with name 'request' to test that it doesn't conflict with the // method arguments with the same name, see issue #159. - final keywordRequest = MethodDescriptorProto() - ..name = 'Request' - ..inputType = '.Input' - ..outputType = '.Output' - ..clientStreaming = false - ..serverStreaming = false; + final keywordRequest = + MethodDescriptorProto() + ..name = 'Request' + ..inputType = '.Input' + ..outputType = '.Output' + ..clientStreaming = false + ..serverStreaming = false; final serviceOptions = ServiceOptions(); serviceOptions.setExtension(Client.defaultHost, 'www.example.com'); @@ -326,22 +385,24 @@ void main() { 'https://www.googleapis.com/auth/datastore', ); - final sd = ServiceDescriptorProto() - ..name = 'Test' - ..options = serviceOptions - ..method.addAll([ - unary, - clientStreaming, - serverStreaming, - bidirectional, - keywordCall, - keywordRequest - ]); - - final fd = FileDescriptorProto() - ..name = 'test' - ..messageType.addAll([input, output]) - ..service.add(sd); + final sd = + ServiceDescriptorProto() + ..name = 'Test' + ..options = serviceOptions + ..method.addAll([ + unary, + clientStreaming, + serverStreaming, + bidirectional, + keywordCall, + keywordRequest, + ]); + + final fd = + FileDescriptorProto() + ..name = 'test' + ..messageType.addAll([input, output]) + ..service.add(sd); final options = GenerationOptions(useGrpc: true); @@ -386,82 +447,91 @@ void main() { // } // Description of package1.proto. - final md1 = DescriptorProto() - ..name = 'M' - ..field.addAll([ - // optional M m = 1; - FieldDescriptorProto() - ..name = 'm' - ..jsonName = 'm' - ..number = 1 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_MESSAGE - ..typeName = '.p1.M', - ]); - final fd1 = FileDescriptorProto() - ..package = 'p1' - ..name = 'package1.proto' - ..messageType.add(md1); + final md1 = + DescriptorProto() + ..name = 'M' + ..field.addAll([ + // optional M m = 1; + FieldDescriptorProto() + ..name = 'm' + ..jsonName = 'm' + ..number = 1 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_MESSAGE + ..typeName = '.p1.M', + ]); + final fd1 = + FileDescriptorProto() + ..package = 'p1' + ..name = 'package1.proto' + ..messageType.add(md1); // Description of package1.proto. - final md2 = DescriptorProto() - ..name = 'M' - ..field.addAll([ - // optional M m = 1; - FieldDescriptorProto() - ..name = 'x' - ..jsonName = 'x' - ..number = 1 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_MESSAGE - ..typeName = '.p2.M', - ]); - final fd2 = FileDescriptorProto() - ..package = 'p2' - ..name = 'package2.proto' - ..messageType.add(md2); + final md2 = + DescriptorProto() + ..name = 'M' + ..field.addAll([ + // optional M m = 1; + FieldDescriptorProto() + ..name = 'x' + ..jsonName = 'x' + ..number = 1 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_MESSAGE + ..typeName = '.p2.M', + ]); + final fd2 = + FileDescriptorProto() + ..package = 'p2' + ..name = 'package2.proto' + ..messageType.add(md2); // Description of test.proto. - final md = DescriptorProto() - ..name = 'M' - ..field.addAll([ - // optional M m = 1; - FieldDescriptorProto() - ..name = 'm' - ..jsonName = 'm' - ..number = 1 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_MESSAGE - ..typeName = '.M', - // optional p1.M m1 = 2; - FieldDescriptorProto() - ..name = 'm1' - ..jsonName = 'm1' - ..number = 2 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_MESSAGE - ..typeName = '.p1.M', - // optional p2.M m2 = 3; - FieldDescriptorProto() - ..name = 'm2' - ..jsonName = 'm2' - ..number = 3 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_MESSAGE - ..typeName = '.p2.M', - ]); - final fd = FileDescriptorProto() - ..name = 'test.proto' - ..messageType.add(md); + final md = + DescriptorProto() + ..name = 'M' + ..field.addAll([ + // optional M m = 1; + FieldDescriptorProto() + ..name = 'm' + ..jsonName = 'm' + ..number = 1 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_MESSAGE + ..typeName = '.M', + // optional p1.M m1 = 2; + FieldDescriptorProto() + ..name = 'm1' + ..jsonName = 'm1' + ..number = 2 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_MESSAGE + ..typeName = '.p1.M', + // optional p2.M m2 = 3; + FieldDescriptorProto() + ..name = 'm2' + ..jsonName = 'm2' + ..number = 3 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_MESSAGE + ..typeName = '.p2.M', + ]); + final fd = + FileDescriptorProto() + ..name = 'test.proto' + ..messageType.add(md); fd.dependency.addAll(['package1.proto', 'package2.proto']); - final request = CodeGeneratorRequest() - ..parameter = 'disable_constructor_args'; + final request = + CodeGeneratorRequest()..parameter = 'disable_constructor_args'; final response = CodeGeneratorResponse(); final options = parseGenerationOptions(request, response)!; final fg = FileGenerator(fd, options); - link(options, - [fg, FileGenerator(fd1, options), FileGenerator(fd2, options)]); + link(options, [ + fg, + FileGenerator(fd1, options), + FileGenerator(fd2, options), + ]); expectGolden(fg.generateMainFile().toString(), 'imports.pb.dart'); expectGolden(fg.generateEnumFile().toString(), 'imports.pbjson.dart'); }); diff --git a/protoc_plugin/test/freeze_test.dart b/protoc_plugin/test/freeze_test.dart index e1a489017..9f2849cc0 100644 --- a/protoc_plugin/test/freeze_test.dart +++ b/protoc_plugin/test/freeze_test.dart @@ -10,10 +10,11 @@ import 'gen/nested_message.pb.dart'; void main() { test('testFreezingNestedFields', () { - final top = Top() - ..nestedMessageList.add(Nested()..a = 1) - ..nestedMessageMap[1] = (Nested()..a = 2) - ..nestedMessage = (Nested()..a = 3); + final top = + Top() + ..nestedMessageList.add(Nested()..a = 1) + ..nestedMessageMap[1] = (Nested()..a = 2) + ..nestedMessage = (Nested()..a = 3); // Create aliases to lists, maps, nested messages final list = top.nestedMessageList; @@ -29,25 +30,35 @@ void main() { // Check list field expect(top.nestedMessageList.length, 1); expect(top.nestedMessageList[0].isFrozen, true); - expect(() => top.nestedMessageList.add(Nested()..a = 0), - throwsA(const TypeMatcher())); + expect( + () => top.nestedMessageList.add(Nested()..a = 0), + throwsA(const TypeMatcher()), + ); // Check map field expect(top.nestedMessageMap.length, 1); expect(top.nestedMessageMap[1]!.isFrozen, true); - expect(() => top.nestedMessageMap[2] = Nested()..a = 0, - throwsA(const TypeMatcher())); - expect(() => map[0] = Nested()..a = 0, - throwsA(const TypeMatcher())); + expect( + () => top.nestedMessageMap[2] = Nested()..a = 0, + throwsA(const TypeMatcher()), + ); + expect( + () => map[0] = Nested()..a = 0, + throwsA(const TypeMatcher()), + ); // Check message field expect(top.nestedMessage.isFrozen, true); // Check aliases - expect(() => list.add(Nested()..a = 0), - throwsA(const TypeMatcher())); - expect(() => map[123] = Nested()..a = 0, - throwsA(const TypeMatcher())); + expect( + () => list.add(Nested()..a = 0), + throwsA(const TypeMatcher()), + ); + expect( + () => map[123] = Nested()..a = 0, + throwsA(const TypeMatcher()), + ); expect(list[0].isFrozen, true); expect(map[1]!.isFrozen, true); expect(msg1.isFrozen, true); @@ -58,17 +69,25 @@ void main() { test('frozen messages should not be updated by merge methods', () { final top = TopEntity()..freeze(); - expect(() => top.mergeFromBuffer([]), - throwsA(TypeMatcher())); - - expect(() => top.mergeFromJsonMap({}), - throwsA(TypeMatcher())); - - expect(() => top.mergeFromMessage(TopEntity()), - throwsA(TypeMatcher())); - - expect(() => top.mergeFromProto3Json({}), - throwsA(TypeMatcher())); + expect( + () => top.mergeFromBuffer([]), + throwsA(TypeMatcher()), + ); + + expect( + () => top.mergeFromJsonMap({}), + throwsA(TypeMatcher()), + ); + + expect( + () => top.mergeFromMessage(TopEntity()), + throwsA(TypeMatcher()), + ); + + expect( + () => top.mergeFromProto3Json({}), + throwsA(TypeMatcher()), + ); }); test('nested frozen messages should not be updated by merge methods', () { @@ -85,13 +104,14 @@ void main() { expect(top.id, Int64(123)); expect( - () => top.mergeFromBuffer([ - (4 << 3) | 2, // tag = 4, type = length delimited - 2, // length - (1 << 3) | 0, // tag = 1, type = varint - 123, // int64 id = 123 - ]), - throwsA(TypeMatcher())); + () => top.mergeFromBuffer([ + (4 << 3) | 2, // tag = 4, type = length delimited + 2, // length + (1 << 3) | 0, // tag = 1, type = varint + 123, // int64 id = 123 + ]), + throwsA(TypeMatcher()), + ); } { @@ -101,9 +121,11 @@ void main() { expect(top.id, Int64(123)); expect( - () => top.mergeFromMessage( - TopEntity()..sub = (SubEntity()..id = Int64(123))), - throwsA(TypeMatcher())); + () => top.mergeFromMessage( + TopEntity()..sub = (SubEntity()..id = Int64(123)), + ), + throwsA(TypeMatcher()), + ); } { @@ -113,10 +135,11 @@ void main() { expect(top.id, Int64(123)); expect( - () => top.mergeFromProto3Json({ - 'sub': {'id': 123} - }), - throwsA(TypeMatcher())); + () => top.mergeFromProto3Json({ + 'sub': {'id': 123}, + }), + throwsA(TypeMatcher()), + ); } }); } diff --git a/protoc_plugin/test/generated_message_test.dart b/protoc_plugin/test/generated_message_test.dart index 2e8327583..6d35ac86a 100644 --- a/protoc_plugin/test/generated_message_test.dart +++ b/protoc_plugin/test/generated_message_test.dart @@ -20,13 +20,15 @@ import 'gen/reserved_names_message.pb.dart'; import 'src/test_util.dart'; void main() { - final throwsInvalidProtocolBufferException = - throwsA(TypeMatcher()); + final throwsInvalidProtocolBufferException = throwsA( + TypeMatcher(), + ); test('testProtosShareRepeatedArraysIfDidntChange', () { - final value1 = TestAllTypes() - ..repeatedInt32.add(100) - ..repeatedImportEnum.add(ImportEnum.IMPORT_BAR) - ..repeatedForeignMessage.add(ForeignMessage()); + final value1 = + TestAllTypes() + ..repeatedInt32.add(100) + ..repeatedImportEnum.add(ImportEnum.IMPORT_BAR) + ..repeatedForeignMessage.add(ForeignMessage()); final value2 = value1.deepCopy(); @@ -37,8 +39,10 @@ void main() { test('testDefaultMessageIsReadOnly', () { var message = TestAllTypes(); - expect(message.optionalNestedMessage, - same(TestAllTypes_NestedMessage.getDefault())); + expect( + message.optionalNestedMessage, + same(TestAllTypes_NestedMessage.getDefault()), + ); expect(() { message.optionalNestedMessage.bb = 123; }, throwsUnsupportedError); @@ -71,10 +75,11 @@ void main() { }); test('testRepeatedAppend', () { - final message = TestAllTypes() - ..repeatedInt32.addAll([1, 2, 3, 4]) - ..repeatedForeignEnum.addAll([ForeignEnum.FOREIGN_BAZ]) - ..repeatedForeignMessage.addAll([ForeignMessage()..c = 12]); + final message = + TestAllTypes() + ..repeatedInt32.addAll([1, 2, 3, 4]) + ..repeatedForeignEnum.addAll([ForeignEnum.FOREIGN_BAZ]) + ..repeatedForeignMessage.addAll([ForeignMessage()..c = 12]); expect(message.repeatedInt32, [1, 2, 3, 4]); expect(message.repeatedForeignEnum, [ForeignEnum.FOREIGN_BAZ]); @@ -83,21 +88,21 @@ void main() { }); test('testSettingForeignMessage', () { - final message = TestAllTypes() - ..optionalForeignMessage = (ForeignMessage()..c = 123); + final message = + TestAllTypes()..optionalForeignMessage = (ForeignMessage()..c = 123); - final expectedMessage = TestAllTypes() - ..optionalForeignMessage = (ForeignMessage()..c = 123); + final expectedMessage = + TestAllTypes()..optionalForeignMessage = (ForeignMessage()..c = 123); expect(message, expectedMessage); }); test('testSettingRepeatedForeignMessage', () { - final message = TestAllTypes() - ..repeatedForeignMessage.add(ForeignMessage()..c = 456); + final message = + TestAllTypes()..repeatedForeignMessage.add(ForeignMessage()..c = 456); - final expectedMessage = TestAllTypes() - ..repeatedForeignMessage.add(ForeignMessage()..c = 456); + final expectedMessage = + TestAllTypes()..repeatedForeignMessage.add(ForeignMessage()..c = 456); expect(message, expectedMessage); }); @@ -115,8 +120,10 @@ void main() { expect(message.negInfFloat, same(double.negativeInfinity)); expect(message.nanFloat, same(double.nan)); expect(message.cppTrigraph, '? ? ?? ?? ??? ??/ ??-'); - expect(message.smallInt64.toRadixString(16).toUpperCase(), - '-7FFFFFFFFFFFFFFF'); + expect( + message.smallInt64.toRadixString(16).toUpperCase(), + '-7FFFFFFFFFFFFFFF', + ); }); test('testClear', () { @@ -154,25 +161,28 @@ void main() { }); test('testParsePackedToUnpacked', () { - final message = - TestUnpackedTypes.fromBuffer(getPackedSet().writeToBuffer()); + final message = TestUnpackedTypes.fromBuffer( + getPackedSet().writeToBuffer(), + ); assertUnpackedFieldsSet(message); }); test('testParseUnpackedToPacked', () { - final message = - TestPackedTypes.fromBuffer(getUnpackedSet().writeToBuffer()); + final message = TestPackedTypes.fromBuffer( + getUnpackedSet().writeToBuffer(), + ); assertPackedFieldsSet(message); }); test('testIgnoreJavaMultipleFilesOption', () { // UNSUPPORTED getFile // We mostly just want to check that things compile. - final message = MessageWithNoOuter() - ..nested = (MessageWithNoOuter_NestedMessage()..i = 1) - ..foreign.add(TestAllTypes()..optionalInt32 = 1) - ..nestedEnum = MessageWithNoOuter_NestedEnum.BAZ - ..foreignEnum = EnumWithNoOuter.BAR; + final message = + MessageWithNoOuter() + ..nested = (MessageWithNoOuter_NestedMessage()..i = 1) + ..foreign.add(TestAllTypes()..optionalInt32 = 1) + ..nestedEnum = MessageWithNoOuter_NestedEnum.BAZ + ..foreignEnum = EnumWithNoOuter.BAR; expect(MessageWithNoOuter.fromBuffer(message.writeToBuffer()), message); @@ -188,24 +198,26 @@ void main() { // MultipleFilesTestProto.getDescriptor()); expect( - TestAllExtensions() - .hasExtension(Multiple_files_test.extensionWithOuter), - isFalse); + TestAllExtensions().hasExtension(Multiple_files_test.extensionWithOuter), + isFalse, + ); }); test('testOptionalFieldWithRequiredSubfieldsOptimizedForSize', () { expect(TestOptionalOptimizedForSize().isInitialized(), isTrue); expect( - (TestOptionalOptimizedForSize()..o = TestRequiredOptimizedForSize()) - .isInitialized(), - isFalse); + (TestOptionalOptimizedForSize()..o = TestRequiredOptimizedForSize()) + .isInitialized(), + isFalse, + ); expect( - (TestOptionalOptimizedForSize() - ..o = (TestRequiredOptimizedForSize()..x = 5)) - .isInitialized(), - isTrue); + (TestOptionalOptimizedForSize() + ..o = (TestRequiredOptimizedForSize()..x = 5)) + .isInitialized(), + isTrue, + ); }); test('testSetAllFieldsAndClone', () { @@ -290,7 +302,7 @@ void main() { expect(TestAllTypes_NestedEnum.values, [ TestAllTypes_NestedEnum.FOO, TestAllTypes_NestedEnum.BAR, - TestAllTypes_NestedEnum.BAZ + TestAllTypes_NestedEnum.BAZ, ]); expect(TestAllTypes_NestedEnum.FOO.value, 1); expect(TestAllTypes_NestedEnum.BAR.value, 2); @@ -340,7 +352,7 @@ void main() { 0x00, 0x00, 0x00, 0x00, 0xc0, 0x79, 0x40, 0xc8, 0x04, 0x00, 0xd2, 0x04, 0x03, 0x34, 0x31, 0x35, 0xda, 0x04, 0x03, 0x34, 0x31, 0x36, 0x88, 0x05, 0x01, 0x90, 0x05, 0x04, 0x98, 0x05, 0x07, 0xa2, 0x05, 0x03, 0x34, 0x32, - 0x34, 0xaa, 0x05, 0x03, 0x34, 0x32, 0x35 + 0x34, 0xaa, 0x05, 0x03, 0x34, 0x32, 0x35, ]; expect(getAllSet().writeToBuffer(), goldenMessage); }); @@ -359,18 +371,24 @@ void main() { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa2, 0x06, 0x08, 0x00, 0xc0, 0x18, 0x44, 0x00, 0xc0, 0x31, 0x44, 0xaa, 0x06, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x83, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x86, 0x40, - 0xb2, 0x06, 0x02, 0x01, 0x00, 0xba, 0x06, 0x02, 0x05, 0x06 + 0xb2, 0x06, 0x02, 0x01, 0x00, 0xba, 0x06, 0x02, 0x05, 0x06, ]; expect(getPackedSet().writeToBuffer(), goldenPackedMessage); }); test('testWriteMessageWithNegativeEnumValue', () { final message = SparseEnumMessage()..sparseEnum = TestSparseEnum.SPARSE_E; - expect(message.sparseEnum.value < 0, isTrue, - reason: 'enum.value should be -53452'); + expect( + message.sparseEnum.value < 0, + isTrue, + reason: 'enum.value should be -53452', + ); final message2 = SparseEnumMessage.fromBuffer(message.writeToBuffer()); - expect(message2.sparseEnum, TestSparseEnum.SPARSE_E, - reason: 'should resolve back to SPARSE_E'); + expect( + message2.sparseEnum, + TestSparseEnum.SPARSE_E, + reason: 'should resolve back to SPARSE_E', + ); }); test('testReservedNamesOptional', () { @@ -739,13 +757,15 @@ void main() { }); test('rebuild updates value', () { - final value1 = TestAllTypes() - ..optionalForeignMessage = (ForeignMessage()..c = 18) - ..freeze(); + final value1 = + TestAllTypes() + ..optionalForeignMessage = (ForeignMessage()..c = 18) + ..freeze(); final value2 = value1.rebuild((v) { v.optionalFloat = 50.1; - v.optionalForeignMessage = - v.optionalForeignMessage.rebuild((o) => o.c = 10); + v.optionalForeignMessage = v.optionalForeignMessage.rebuild( + (o) => o.c = 10, + ); }); expect(value2.isFrozen, true); expect(value2.optionalFloat, 50.1); @@ -758,9 +778,10 @@ void main() { }); test('rebuild shares structure', () { - final value1 = TestAllTypes() - ..optionalForeignMessage = (ForeignMessage()..c = 18) - ..freeze(); + final value1 = + TestAllTypes() + ..optionalForeignMessage = (ForeignMessage()..c = 18) + ..freeze(); final value2 = value1.rebuild((v) { v.optionalFloat = 50.1; }); @@ -775,8 +796,10 @@ void main() { final value2 = value1.deepCopy(); assertAllFieldsSet(value2); expect(value2, isNot(same(value1))); - expect(value2.optionalForeignMessage, - isNot(same(value1.optionalForeignMessage))); + expect( + value2.optionalForeignMessage, + isNot(same(value1.optionalForeignMessage)), + ); }); test('deepCopy extensions', () { diff --git a/protoc_plugin/test/goldens/client.pb.dart b/protoc_plugin/test/goldens/client.pb.dart index f35cc451d..72133468c 100644 --- a/protoc_plugin/test/goldens/client.pb.dart +++ b/protoc_plugin/test/goldens/client.pb.dart @@ -4,10 +4,17 @@ class TestApi { TestApi(this._client); $async.Future aMethod( - $pb.ClientContext? ctx, SomeRequest request) => - _client.invoke(ctx, 'Test', 'AMethod', request, SomeReply()); + $pb.ClientContext? ctx, + SomeRequest request, + ) => _client.invoke(ctx, 'Test', 'AMethod', request, SomeReply()); $async.Future<$0.AnotherReply> anotherMethod( - $pb.ClientContext? ctx, $0.EmptyMessage request) => - _client.invoke<$0.AnotherReply>( - ctx, 'Test', 'AnotherMethod', request, $0.AnotherReply()); + $pb.ClientContext? ctx, + $0.EmptyMessage request, + ) => _client.invoke<$0.AnotherReply>( + ctx, + 'Test', + 'AnotherMethod', + request, + $0.AnotherReply(), + ); } diff --git a/protoc_plugin/test/goldens/enum.pbenum.dart b/protoc_plugin/test/goldens/enum.pbenum.dart index de7464f09..4aa604e3a 100644 --- a/protoc_plugin/test/goldens/enum.pbenum.dart +++ b/protoc_plugin/test/goldens/enum.pbenum.dart @@ -1,24 +1,23 @@ class PhoneType extends $pb.ProtobufEnum { - static const PhoneType MOBILE = - PhoneType._(0, _omitEnumNames ? '' : 'MOBILE'); + static const PhoneType MOBILE = PhoneType._( + 0, + _omitEnumNames ? '' : 'MOBILE', + ); static const PhoneType HOME = PhoneType._(1, _omitEnumNames ? '' : 'HOME'); static const PhoneType WORK = PhoneType._(2, _omitEnumNames ? '' : 'WORK'); static const PhoneType BUSINESS = WORK; - static const $core.List values = [ - MOBILE, - HOME, - WORK, - ]; + static const $core.List values = [MOBILE, HOME, WORK]; - static final $core.List _byValue = - $pb.ProtobufEnum.$_initByValueList(values, 2); + static final $core.List _byValue = $pb + .ProtobufEnum.$_initByValueList(values, 2); static PhoneType? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const PhoneType._(super.value, super.name); } -const $core.bool _omitEnumNames = - $core.bool.fromEnvironment('protobuf.omit_enum_names'); +const $core.bool _omitEnumNames = $core.bool.fromEnvironment( + 'protobuf.omit_enum_names', +); diff --git a/protoc_plugin/test/goldens/extension.pb.dart b/protoc_plugin/test/goldens/extension.pb.dart index 86888691b..c53762fbf 100644 --- a/protoc_plugin/test/goldens/extension.pb.dart +++ b/protoc_plugin/test/goldens/extension.pb.dart @@ -1,12 +1,15 @@ class Card { static final clientInfo = $pb.Extension<$core.String>( - _omitMessageNames ? '' : 'Card', - _omitFieldNames ? '' : 'clientInfo', - 261486461, - $pb.PbFieldType.OS); + _omitMessageNames ? '' : 'Card', + _omitFieldNames ? '' : 'clientInfo', + 261486461, + $pb.PbFieldType.OS, + ); - const $core.bool _omitFieldNames = - $core.bool.fromEnvironment('protobuf.omit_field_names'); - const $core.bool _omitMessageNames = - $core.bool.fromEnvironment('protobuf.omit_message_names'); + const $core.bool _omitFieldNames = $core.bool.fromEnvironment( + 'protobuf.omit_field_names', + ); + const $core.bool _omitMessageNames = $core.bool.fromEnvironment( + 'protobuf.omit_message_names', + ); } diff --git a/protoc_plugin/test/goldens/messageGenerator.pb.dart b/protoc_plugin/test/goldens/messageGenerator.pb.dart index 6871bed3b..6dd11f52e 100644 --- a/protoc_plugin/test/goldens/messageGenerator.pb.dart +++ b/protoc_plugin/test/goldens/messageGenerator.pb.dart @@ -3,25 +3,36 @@ class PhoneNumber extends $pb.GeneratedMessage { PhoneNumber._(); - factory PhoneNumber.fromBuffer($core.List<$core.int> data, - [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => - create()..mergeFromBuffer(data, registry); - factory PhoneNumber.fromJson($core.String json, - [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => - create()..mergeFromJson(json, registry); + factory PhoneNumber.fromBuffer( + $core.List<$core.int> data, [ + $pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY, + ]) => create()..mergeFromBuffer(data, registry); + factory PhoneNumber.fromJson( + $core.String json, [ + $pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY, + ]) => create()..mergeFromJson(json, registry); - static final $pb.BuilderInfo _i = $pb.BuilderInfo( - _omitMessageNames ? '' : 'PhoneNumber', - createEmptyInstance: create) - ..aQS(1, _omitFieldNames ? '' : 'number') - ..e( - 2, _omitFieldNames ? '' : 'type', $pb.PbFieldType.OE, - defaultOrMaker: PhoneNumber_PhoneType.MOBILE, - valueOf: PhoneNumber_PhoneType.valueOf, - enumValues: PhoneNumber_PhoneType.values) - ..a<$core.String>(3, _omitFieldNames ? '' : 'name', $pb.PbFieldType.OS, - defaultOrMaker: '\$') - ..aOS(4, _omitFieldNames ? '' : 'deprecatedField'); + static final $pb.BuilderInfo _i = + $pb.BuilderInfo( + _omitMessageNames ? '' : 'PhoneNumber', + createEmptyInstance: create, + ) + ..aQS(1, _omitFieldNames ? '' : 'number') + ..e( + 2, + _omitFieldNames ? '' : 'type', + $pb.PbFieldType.OE, + defaultOrMaker: PhoneNumber_PhoneType.MOBILE, + valueOf: PhoneNumber_PhoneType.valueOf, + enumValues: PhoneNumber_PhoneType.values, + ) + ..a<$core.String>( + 3, + _omitFieldNames ? '' : 'name', + $pb.PbFieldType.OS, + defaultOrMaker: '\$', + ) + ..aOS(4, _omitFieldNames ? '' : 'deprecatedField'); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') PhoneNumber clone() => PhoneNumber()..mergeFromMessage(this); @@ -39,8 +50,10 @@ class PhoneNumber extends $pb.GeneratedMessage { PhoneNumber createEmptyInstance() => create(); static $pb.PbList createRepeated() => $pb.PbList(); @$core.pragma('dart2js:noInline') - static PhoneNumber getDefault() => _defaultInstance ??= - $pb.GeneratedMessage.$_defaultFor(create); + static PhoneNumber getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor( + create, + ); static PhoneNumber? _defaultInstance; @$pb.TagNumber(1) @@ -84,7 +97,9 @@ class PhoneNumber extends $pb.GeneratedMessage { void clearDeprecatedField() => $_clearField(4); } -const $core.bool _omitFieldNames = - $core.bool.fromEnvironment('protobuf.omit_field_names'); -const $core.bool _omitMessageNames = - $core.bool.fromEnvironment('protobuf.omit_message_names'); +const $core.bool _omitFieldNames = $core.bool.fromEnvironment( + 'protobuf.omit_field_names', +); +const $core.bool _omitMessageNames = $core.bool.fromEnvironment( + 'protobuf.omit_message_names', +); diff --git a/protoc_plugin/test/goldens/messageGeneratorEnums.pb.dart b/protoc_plugin/test/goldens/messageGeneratorEnums.pb.dart index 4ac231317..494f2509e 100644 --- a/protoc_plugin/test/goldens/messageGeneratorEnums.pb.dart +++ b/protoc_plugin/test/goldens/messageGeneratorEnums.pb.dart @@ -1,27 +1,30 @@ class PhoneNumber_PhoneType extends $pb.ProtobufEnum { - static const PhoneNumber_PhoneType MOBILE = - PhoneNumber_PhoneType._(0, _omitEnumNames ? '' : 'MOBILE'); - static const PhoneNumber_PhoneType HOME = - PhoneNumber_PhoneType._(1, _omitEnumNames ? '' : 'HOME'); - static const PhoneNumber_PhoneType WORK = - PhoneNumber_PhoneType._(2, _omitEnumNames ? '' : 'WORK'); + static const PhoneNumber_PhoneType MOBILE = PhoneNumber_PhoneType._( + 0, + _omitEnumNames ? '' : 'MOBILE', + ); + static const PhoneNumber_PhoneType HOME = PhoneNumber_PhoneType._( + 1, + _omitEnumNames ? '' : 'HOME', + ); + static const PhoneNumber_PhoneType WORK = PhoneNumber_PhoneType._( + 2, + _omitEnumNames ? '' : 'WORK', + ); static const PhoneNumber_PhoneType BUSINESS = WORK; static const $core.List values = - [ - MOBILE, - HOME, - WORK, - ]; + [MOBILE, HOME, WORK]; - static final $core.List _byValue = - $pb.ProtobufEnum.$_initByValueList(values, 2); + static final $core.List _byValue = $pb + .ProtobufEnum.$_initByValueList(values, 2); static PhoneNumber_PhoneType? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const PhoneNumber_PhoneType._(super.value, super.name); } -const $core.bool _omitEnumNames = - $core.bool.fromEnvironment('protobuf.omit_enum_names'); +const $core.bool _omitEnumNames = $core.bool.fromEnvironment( + 'protobuf.omit_enum_names', +); diff --git a/protoc_plugin/test/goldens/serviceGenerator.pb.dart b/protoc_plugin/test/goldens/serviceGenerator.pb.dart index d406ac716..067ea4f0d 100644 --- a/protoc_plugin/test/goldens/serviceGenerator.pb.dart +++ b/protoc_plugin/test/goldens/serviceGenerator.pb.dart @@ -1,8 +1,12 @@ abstract class TestServiceBase extends $pb.GeneratedService { $async.Future<$0.SomeReply> aMethod( - $pb.ServerContext ctx, $0.SomeRequest request); + $pb.ServerContext ctx, + $0.SomeRequest request, + ); $async.Future<$1.AnotherReply> anotherMethod( - $pb.ServerContext ctx, $1.EmptyMessage request); + $pb.ServerContext ctx, + $1.EmptyMessage request, + ); $pb.GeneratedMessage createRequest($core.String methodName) { switch (methodName) { @@ -15,8 +19,11 @@ abstract class TestServiceBase extends $pb.GeneratedService { } } - $async.Future<$pb.GeneratedMessage> handleCall($pb.ServerContext ctx, - $core.String methodName, $pb.GeneratedMessage request) { + $async.Future<$pb.GeneratedMessage> handleCall( + $pb.ServerContext ctx, + $core.String methodName, + $pb.GeneratedMessage request, + ) { switch (methodName) { case 'AMethod': return aMethod(ctx, request as $0.SomeRequest); @@ -29,5 +36,5 @@ abstract class TestServiceBase extends $pb.GeneratedService { $core.Map<$core.String, $core.dynamic> get $json => TestServiceBase$json; $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> - get $messageJson => TestServiceBase$messageJson; + get $messageJson => TestServiceBase$messageJson; } diff --git a/protoc_plugin/test/hash_code_test.dart b/protoc_plugin/test/hash_code_test.dart index 849e8d2b6..8e02a5479 100644 --- a/protoc_plugin/test/hash_code_test.dart +++ b/protoc_plugin/test/hash_code_test.dart @@ -133,16 +133,18 @@ void main() { }); test('testHashCodeCombined', () { - final m1 = TestAllTypes() - ..optionalInt32 = 42 - ..optionalInt64 = Int64(42) - ..optionalString = 'Dart' - ..optionalNestedEnum = TestAllTypes_NestedEnum.BAR; - final m2 = TestAllTypes() - ..optionalInt32 = 42 - ..optionalInt64 = Int64(42) - ..optionalString = 'Dart' - ..optionalNestedEnum = TestAllTypes_NestedEnum.BAR; + final m1 = + TestAllTypes() + ..optionalInt32 = 42 + ..optionalInt64 = Int64(42) + ..optionalString = 'Dart' + ..optionalNestedEnum = TestAllTypes_NestedEnum.BAR; + final m2 = + TestAllTypes() + ..optionalInt32 = 42 + ..optionalInt64 = Int64(42) + ..optionalString = 'Dart' + ..optionalNestedEnum = TestAllTypes_NestedEnum.BAR; expect(m1.hashCode, m2.hashCode); m1.repeatedInt32 diff --git a/protoc_plugin/test/high_tagnumber_test.dart b/protoc_plugin/test/high_tagnumber_test.dart index 9769ae9b5..c230d48ff 100644 --- a/protoc_plugin/test/high_tagnumber_test.dart +++ b/protoc_plugin/test/high_tagnumber_test.dart @@ -20,8 +20,9 @@ void main() { test('unknown fields', () { final empty = Empty.fromBuffer((M()..a = 44).writeToBuffer()); expect(empty.unknownFields.isEmpty, false); - expect(empty.unknownFields.getField(M().info_.tagNumber('a')!)!.varints, - [Int64(44)]); + expect(empty.unknownFields.getField(M().info_.tagNumber('a')!)!.varints, [ + Int64(44), + ]); expect(M.fromBuffer(empty.writeToBuffer()).a, 44); }); } diff --git a/protoc_plugin/test/indenting_writer_test.dart b/protoc_plugin/test/indenting_writer_test.dart index 6af479758..e9e9916b1 100644 --- a/protoc_plugin/test/indenting_writer_test.dart +++ b/protoc_plugin/test/indenting_writer_test.dart @@ -29,13 +29,14 @@ class test { final out = IndentingWriter(filename: 'sample.proto'); out.print('13 characters'); out.printAnnotated('sample text', [ - NamedLocation(name: 'text', fieldPathSegment: [1, 2, 3], start: 7) + NamedLocation(name: 'text', fieldPathSegment: [1, 2, 3], start: 7), ]); - final expected = GeneratedCodeInfo_Annotation() - ..path.addAll([1, 2, 3]) - ..sourceFile = 'sample.proto' - ..begin = 20 - ..end = 24; + final expected = + GeneratedCodeInfo_Annotation() + ..path.addAll([1, 2, 3]) + ..sourceFile = 'sample.proto' + ..begin = 20 + ..end = 24; final annotation = out.sourceLocationInfo.annotation[0]; expect(annotation, equals(expected)); }); @@ -43,8 +44,9 @@ class test { test('IndentingWriter annotation counts indents correctly', () { final out = IndentingWriter(filename: ''); out.addBlock('34 characters including newline {', '}', () { - out.printlnAnnotated('sample text', - [NamedLocation(name: 'sample', fieldPathSegment: [], start: 0)]); + out.printlnAnnotated('sample text', [ + NamedLocation(name: 'sample', fieldPathSegment: [], start: 0), + ]); }); final annotation = out.sourceLocationInfo.annotation[0]; // The indent is 2 characters, so these should be shifted by 2. @@ -55,8 +57,9 @@ class test { test('IndentingWriter annotations counts multiline output correctly', () { final out = IndentingWriter(filename: ''); out.print('20 characters\ntotal\n'); - out.printlnAnnotated('20 characters before this', - [NamedLocation(name: 'ch', fieldPathSegment: [], start: 3)]); + out.printlnAnnotated('20 characters before this', [ + NamedLocation(name: 'ch', fieldPathSegment: [], start: 3), + ]); final annotation = out.sourceLocationInfo.annotation[0]; expect(annotation.begin, equals(23)); expect(annotation.end, equals(25)); @@ -75,11 +78,14 @@ class test { importWriter.addImport('dart:convert', prefix: 'convert'); importWriter.addImport('dart:async'); - expect(importWriter.emit(), equals(''' + expect( + importWriter.emit(), + equals(''' import 'dart:async'; import 'dart:convert' as convert; import 'dart:typed_data'; -''')); +'''), + ); }); test('grouping', () { @@ -87,13 +93,16 @@ import 'dart:typed_data'; importWriter.addImport('package:path/path.dart', prefix: 'path'); importWriter.addImport('dart:convert', prefix: 'convert'); - expect(importWriter.emit(), equals(''' + expect( + importWriter.emit(), + equals(''' import 'dart:convert' as convert; import 'package:path/path.dart' as path; import 'string_utilities.dart'; -''')); +'''), + ); }); }); } diff --git a/protoc_plugin/test/json_test.dart b/protoc_plugin/test/json_test.dart index 80f8735b3..7c6b27f74 100644 --- a/protoc_plugin/test/json_test.dart +++ b/protoc_plugin/test/json_test.dart @@ -12,7 +12,8 @@ import 'gen/map_enum_value.pb.dart'; import 'src/test_util.dart'; void main() { - final testAllJsonTypes = '{"1":101,"2":"102","3":103,"4":"104",' + final testAllJsonTypes = + '{"1":101,"2":"102","3":103,"4":"104",' '"5":105,"6":"106","7":107,"8":"108","9":109,"10":"110","11":111,' '"12":112,"13":true,"14":"115","15":"MTE2","16":{"17":117},' '"18":{"1":118},"19":{"1":119},"20":{"1":120},"21":3,"22":6,"23":9,' @@ -33,8 +34,9 @@ void main() { Matcher expectedJson(String from, String to) { final expectedJson = testAllJsonTypes.replaceAll(from, to); return predicate( - (GeneratedMessage message) => message.writeToJson() == expectedJson, - 'Incorrect output'); + (GeneratedMessage message) => message.writeToJson() == expectedJson, + 'Incorrect output', + ); } test('testUnsignedOutput', () { @@ -55,43 +57,65 @@ void main() { expect(getAllSet().writeToJson(), testAllJsonTypes); // Test empty list. - expect(getAllSet()..repeatedBool.clear(), - expectedJson('"43":[true,false],', '')); + expect( + getAllSet()..repeatedBool.clear(), + expectedJson('"43":[true,false],', ''), + ); // Test negative number. - expect(getAllSet()..optionalInt32 = -1234567, - expectedJson(':101,', ':-1234567,')); + expect( + getAllSet()..optionalInt32 = -1234567, + expectedJson(':101,', ':-1234567,'), + ); // All 64-bit numbers are quoted. - expect(getAllSet()..optionalInt64 = make64(0, 0x200000), - expectedJson(':"102",', ':"9007199254740992",')); - expect(getAllSet()..optionalInt64 = make64(1, 0x200000), - expectedJson(':"102",', ':"9007199254740993",')); - expect(getAllSet()..optionalInt64 = -make64(0, 0x200000), - expectedJson(':"102",', ':"-9007199254740992",')); - expect(getAllSet()..optionalInt64 = -make64(1, 0x200000), - expectedJson(':"102",', ':"-9007199254740993",')); + expect( + getAllSet()..optionalInt64 = make64(0, 0x200000), + expectedJson(':"102",', ':"9007199254740992",'), + ); + expect( + getAllSet()..optionalInt64 = make64(1, 0x200000), + expectedJson(':"102",', ':"9007199254740993",'), + ); + expect( + getAllSet()..optionalInt64 = -make64(0, 0x200000), + expectedJson(':"102",', ':"-9007199254740992",'), + ); + expect( + getAllSet()..optionalInt64 = -make64(1, 0x200000), + expectedJson(':"102",', ':"-9007199254740993",'), + ); // Quotes, backslashes, and control characters in strings are quoted. - expect(getAllSet()..optionalString = 'a\u0000b\u0001cd\\e"fg', - expectedJson(':"115",', ':"a\\u0000b\\u0001cd\\\\e\\"fg",')); + expect( + getAllSet()..optionalString = 'a\u0000b\u0001cd\\e"fg', + expectedJson(':"115",', ':"a\\u0000b\\u0001cd\\\\e\\"fg",'), + ); }); test('testBase64Encode', () { - expect(getAllSet()..optionalBytes = 'Hello, world'.codeUnits, - expectedJson(':"MTE2",', ':"SGVsbG8sIHdvcmxk",')); + expect( + getAllSet()..optionalBytes = 'Hello, world'.codeUnits, + expectedJson(':"MTE2",', ':"SGVsbG8sIHdvcmxk",'), + ); - expect(getAllSet()..optionalBytes = 'Hello, world!'.codeUnits, - expectedJson(':"MTE2",', ':"SGVsbG8sIHdvcmxkIQ==",')); + expect( + getAllSet()..optionalBytes = 'Hello, world!'.codeUnits, + expectedJson(':"MTE2",', ':"SGVsbG8sIHdvcmxkIQ==",'), + ); - expect(getAllSet()..optionalBytes = 'Hello, world!!'.codeUnits, - expectedJson(':"MTE2",', ':"SGVsbG8sIHdvcmxkISE=",')); + expect( + getAllSet()..optionalBytes = 'Hello, world!!'.codeUnits, + expectedJson(':"MTE2",', ':"SGVsbG8sIHdvcmxkISE=",'), + ); // An empty list should not appear in the output. expect(getAllSet()..optionalBytes = [], expectedJson('"15":"MTE2",', '')); - expect(getAllSet()..optionalBytes = 'a'.codeUnits, - expectedJson(':"MTE2",', ':"YQ==",')); + expect( + getAllSet()..optionalBytes = 'a'.codeUnits, + expectedJson(':"MTE2",', ':"YQ==",'), + ); }); test('testBase64Decode', () { @@ -103,10 +127,14 @@ void main() { expect(optionalBytes(':"MTE2",', ':"SGVsbG8sIHdvcmxk",'), 'Hello, world'); expect( - optionalBytes(':"MTE2",', ':"SGVsbG8sIHdvcmxkIQ==",'), 'Hello, world!'); + optionalBytes(':"MTE2",', ':"SGVsbG8sIHdvcmxkIQ==",'), + 'Hello, world!', + ); - expect(optionalBytes(':"MTE2",', ':"SGVsbG8sIHdvcmxkISE=",'), - 'Hello, world!!'); + expect( + optionalBytes(':"MTE2",', ':"SGVsbG8sIHdvcmxkISE=",'), + 'Hello, world!!', + ); // Remove optionalBytes tag, reads back as empty list, hence empty string. expect(optionalBytes('"15":"MTE2",', ''), isEmpty); @@ -119,7 +147,8 @@ void main() { test('testParseUnsigned', () { final parsed = TestAllTypes.fromJson( - '{"4":"17293822573397606400","8":"17293822573397606401"}'); + '{"4":"17293822573397606400","8":"17293822573397606401"}', + ); final expected = TestAllTypes(); expected.optionalUint64 = Int64.parseHex('f0000000ffff0000'); expected.optionalFixed64 = Int64.parseHex('f0000000ffff0001'); @@ -159,7 +188,8 @@ void main() { test('testParseUnsignedLegacy', () { final parsed = TestAllTypes.fromJson( - '{"4":"-1152921500311945216","8":"-1152921500311945215"}'); + '{"4":"-1152921500311945216","8":"-1152921500311945215"}', + ); final expected = TestAllTypes(); expected.optionalUint64 = Int64.parseHex('f0000000ffff0000'); expected.optionalFixed64 = Int64.parseHex('f0000000ffff0001'); @@ -191,8 +221,10 @@ void main() { test('testExtensionsParse', () { final registry = getExtensionRegistry(); - expect(TestAllExtensions.fromJson(testAllJsonTypes, registry), - getAllExtensionsSet()); + expect( + TestAllExtensions.fromJson(testAllJsonTypes, registry), + getAllExtensionsSet(), + ); }); test('testUnknownEnumValueInOptionalField', () { @@ -212,15 +244,16 @@ void main() { // the default enum value (FOO). message = TestAllTypes.fromJson('{"51": [1, 4, 2, 4, 1, 4]}'); expect( - message.repeatedNestedEnum, - equals([ - TestAllTypes_NestedEnum.FOO, - TestAllTypes_NestedEnum.FOO, - TestAllTypes_NestedEnum.BAR, - TestAllTypes_NestedEnum.FOO, - TestAllTypes_NestedEnum.FOO, - TestAllTypes_NestedEnum.FOO - ])); + message.repeatedNestedEnum, + equals([ + TestAllTypes_NestedEnum.FOO, + TestAllTypes_NestedEnum.FOO, + TestAllTypes_NestedEnum.BAR, + TestAllTypes_NestedEnum.FOO, + TestAllTypes_NestedEnum.FOO, + TestAllTypes_NestedEnum.FOO, + ]), + ); }); test('testUnknownEnumValueInMapField', () { diff --git a/protoc_plugin/test/map_field_test.dart b/protoc_plugin/test/map_field_test.dart index e8a8d4290..7667bca46 100644 --- a/protoc_plugin/test/map_field_test.dart +++ b/protoc_plugin/test/map_field_test.dart @@ -172,31 +172,34 @@ void main() { }); test( - 'PbMap` is equal to another PbMap with equal key/value pairs in any order', - () { - final t = TestMap() - ..int32ToStringField[2] = 'test2' - ..int32ToStringField[1] = 'test'; - final t2 = TestMap() - ..int32ToStringField[1] = 'test' - ..int32ToStringField[2] = 'test2'; - final t3 = TestMap()..int32ToStringField[1] = 'test'; - - final m = t.int32ToStringField; - final m2 = t2.int32ToStringField; - final m3 = t3.int32ToStringField; - - expect(t, t2); - expect(t.hashCode, t2.hashCode); - - expect(m, m2); - expect(m == m2, isTrue); - expect(m.hashCode, m2.hashCode); - - expect(m, isNot(m3)); - expect(m == m3, isFalse); - expect(m.hashCode, isNot(m3.hashCode)); - }); + 'PbMap` is equal to another PbMap with equal key/value pairs in any order', + () { + final t = + TestMap() + ..int32ToStringField[2] = 'test2' + ..int32ToStringField[1] = 'test'; + final t2 = + TestMap() + ..int32ToStringField[1] = 'test' + ..int32ToStringField[2] = 'test2'; + final t3 = TestMap()..int32ToStringField[1] = 'test'; + + final m = t.int32ToStringField; + final m2 = t2.int32ToStringField; + final m3 = t3.int32ToStringField; + + expect(t, t2); + expect(t.hashCode, t2.hashCode); + + expect(m, m2); + expect(m == m2, isTrue); + expect(m.hashCode, m2.hashCode); + + expect(m, isNot(m3)); + expect(m == m3, isFalse); + expect(m.hashCode, isNot(m3.hashCode)); + }, + ); test('Unitialized map field is equal to initialized', () { final testMap1 = TestMap(); @@ -219,11 +222,13 @@ void main() { other.mergeFromMessage(testMap); expectMapValuesSet(other); - testMap = TestMap() - ..int32ToMessageField[1] = (TestMap_MessageValue()..value = 42) - ..int32ToMessageField[2] = (TestMap_MessageValue()..value = 44); - other = TestMap() - ..int32ToMessageField[1] = (TestMap_MessageValue()..secondValue = 43); + testMap = + TestMap() + ..int32ToMessageField[1] = (TestMap_MessageValue()..value = 42) + ..int32ToMessageField[2] = (TestMap_MessageValue()..value = 44); + other = + TestMap() + ..int32ToMessageField[1] = (TestMap_MessageValue()..secondValue = 43); testMap.mergeFromMessage(other); expect(testMap.int32ToMessageField[1]!.value, 0); @@ -235,8 +240,10 @@ void main() { final testMap = TestMap()..int32ToStringField[1] = 'foo'; final testMap2 = TestMap()..int32ToStringField[1] = 'bar'; - final merge = TestMap.fromBuffer( - [...testMap.writeToBuffer(), ...testMap2.writeToBuffer()]); + final merge = TestMap.fromBuffer([ + ...testMap.writeToBuffer(), + ...testMap2.writeToBuffer(), + ]); // When parsing from the wire, if there are duplicate map keys the last key // seen should be used. @@ -270,14 +277,22 @@ void main() { setValues(testMap); testMap.freeze(); - expect(() => updateValues(testMap), - throwsA(const TypeMatcher())); - expect(() => testMap.int32ToMessageField[1]!.value = 42, - throwsA(const TypeMatcher())); - expect(() => testMap.int32ToStringField.remove(1), - throwsA(const TypeMatcher())); - expect(() => testMap.int32ToStringField.clear(), - throwsA(const TypeMatcher())); + expect( + () => updateValues(testMap), + throwsA(const TypeMatcher()), + ); + expect( + () => testMap.int32ToMessageField[1]!.value = 42, + throwsA(const TypeMatcher()), + ); + expect( + () => testMap.int32ToStringField.remove(1), + throwsA(const TypeMatcher()), + ); + expect( + () => testMap.int32ToStringField.clear(), + throwsA(const TypeMatcher()), + ); }); test('Values for different keys are not merged together when decoding', () { @@ -305,10 +320,14 @@ void main() { test('Calling getField on map fields using reflective API works.', () { final testMap = TestMap(); - final mapFieldInfo = testMap.info_.fieldInfo.values - .where((fieldInfo) => - fieldInfo is MapFieldInfo && fieldInfo.name == 'int32ToBytesField') - .single; + final mapFieldInfo = + testMap.info_.fieldInfo.values + .where( + (fieldInfo) => + fieldInfo is MapFieldInfo && + fieldInfo.name == 'int32ToBytesField', + ) + .single; final value = testMap.getField(mapFieldInfo.tagNumber); expect(value is Map>, true); }); @@ -316,25 +335,38 @@ void main() { test('Parses null keys and values', () { // Use a desugared version of the message to create missing // values in the serialized form. - final d = Desugared() - ..int32ToStringField.add(Desugared_Int32ToString() - ..clearKey() - ..value = 'abc') - ..int32ToStringField.add(Desugared_Int32ToString() - ..key = 42 - ..clearValue()) - ..int32ToStringField.add(Desugared_Int32ToString() - ..key = 11 - ..value = 'def') - ..stringToInt32Field.add(Desugared_StringToInt32() - ..clearKey() - ..value = 11) - ..stringToInt32Field.add(Desugared_StringToInt32() - ..key = 'abc' - ..clearValue()) - ..stringToInt32Field.add(Desugared_StringToInt32() - ..key = 'def' - ..value = 42); + final d = + Desugared() + ..int32ToStringField.add( + Desugared_Int32ToString() + ..clearKey() + ..value = 'abc', + ) + ..int32ToStringField.add( + Desugared_Int32ToString() + ..key = 42 + ..clearValue(), + ) + ..int32ToStringField.add( + Desugared_Int32ToString() + ..key = 11 + ..value = 'def', + ) + ..stringToInt32Field.add( + Desugared_StringToInt32() + ..clearKey() + ..value = 11, + ) + ..stringToInt32Field.add( + Desugared_StringToInt32() + ..key = 'abc' + ..clearValue(), + ) + ..stringToInt32Field.add( + Desugared_StringToInt32() + ..key = 'def' + ..value = 42, + ); final m = TestMap.fromBuffer(d.writeToBuffer()); expect(m.int32ToStringField[0], 'abc'); @@ -381,7 +413,9 @@ void main() { ]; final message = TestMap.fromBuffer(messageBytes); expect( - message, TestMap()..int32ToMessageField[0] = TestMap_MessageValue()); + message, + TestMap()..int32ToMessageField[0] = TestMap_MessageValue(), + ); } { @@ -391,7 +425,9 @@ void main() { ]; final message = TestMap.fromBuffer(messageBytes); expect( - message, TestMap()..int32ToEnumField[0] = TestMap_EnumValue.DEFAULT); + message, + TestMap()..int32ToEnumField[0] = TestMap_EnumValue.DEFAULT, + ); } }); @@ -406,7 +442,9 @@ void main() { ]; final message = TestMap.fromBuffer(messageBytes); expect( - message, TestMap()..int32ToMessageField[1] = TestMap_MessageValue()); + message, + TestMap()..int32ToMessageField[1] = TestMap_MessageValue(), + ); } { @@ -418,7 +456,9 @@ void main() { ]; final message = TestMap.fromBuffer(messageBytes); expect( - message, TestMap()..int32ToEnumField[1] = TestMap_EnumValue.DEFAULT); + message, + TestMap()..int32ToEnumField[1] = TestMap_EnumValue.DEFAULT, + ); } }); @@ -433,7 +473,9 @@ void main() { ]; final message = TestMap.fromBuffer(messageBytes); expect( - message, TestMap()..int32ToMessageField[0] = TestMap_MessageValue()); + message, + TestMap()..int32ToMessageField[0] = TestMap_MessageValue(), + ); } { diff --git a/protoc_plugin/test/map_test.dart b/protoc_plugin/test/map_test.dart index 53caa6096..3002324b8 100644 --- a/protoc_plugin/test/map_test.dart +++ b/protoc_plugin/test/map_test.dart @@ -49,11 +49,18 @@ void main() { test('operator []= throws exception for invalid key', () { final rec = pb.Rec(); - expect(() { - rec['unknown'] = 123; - }, - throwsA(isA().having((p0) => p0.message, 'message', - "field 'unknown' not found in protobuf_unittest.Rec"))); + expect( + () { + rec['unknown'] = 123; + }, + throwsA( + isA().having( + (p0) => p0.message, + 'message', + "field 'unknown' not found in protobuf_unittest.Rec", + ), + ), + ); }); test('operator []= throws exception for repeated field', () { @@ -106,11 +113,18 @@ void main() { test("remove isn't supported", () { final rec = pb.Rec(); rec.str = 'hello'; - expect(() { - rec.remove('str'); - }, - throwsA(isA().having((p0) => p0.message, 'message', - 'remove() not supported by protobuf_unittest.Rec'))); + expect( + () { + rec.remove('str'); + }, + throwsA( + isA().having( + (p0) => p0.message, + 'message', + 'remove() not supported by protobuf_unittest.Rec', + ), + ), + ); expect(rec.str, 'hello'); }); @@ -139,7 +153,7 @@ void main() { final rec = pb.Rec(); expect(() { rec.addAll({ - 'nums': [1, 2, 3] + 'nums': [1, 2, 3], }); }, throwsArgumentError); }); diff --git a/protoc_plugin/test/merge_test.dart b/protoc_plugin/test/merge_test.dart index 731bbb544..66f24c5d0 100644 --- a/protoc_plugin/test/merge_test.dart +++ b/protoc_plugin/test/merge_test.dart @@ -9,50 +9,58 @@ import 'gen/foo.pb.dart' as pb; void main() { test('merges child message', () { - final top = pb.Outer() - ..id = Int64(1) - ..value = 'sss' - ..strings.addAll(['s1', 's2']) - ..inner = (pb.Inner() - ..id = Int64(2) - ..value = 'sub' - ..strings.addAll(['sub1', 'sub2'])); + final top = + pb.Outer() + ..id = Int64(1) + ..value = 'sss' + ..strings.addAll(['s1', 's2']) + ..inner = + (pb.Inner() + ..id = Int64(2) + ..value = 'sub' + ..strings.addAll(['sub1', 'sub2'])); - final update = pb.Outer() - ..id = Int64(1) - ..value = 'new' - ..inner = (pb.Inner()..id = Int64(3)); + final update = + pb.Outer() + ..id = Int64(1) + ..value = 'new' + ..inner = (pb.Inner()..id = Int64(3)); top.mergeFromMessage(update); - final expected = pb.Outer() - ..id = Int64(1) - ..value = 'new' - ..strings.addAll(['s1', 's2']) - // This is properly merged. - ..inner = (pb.Inner() - ..id = Int64(3) - ..value = 'sub' - ..strings.addAll(['sub1', 'sub2'])); + final expected = + pb.Outer() + ..id = Int64(1) + ..value = 'new' + ..strings.addAll(['s1', 's2']) + // This is properly merged. + ..inner = + (pb.Inner() + ..id = Int64(3) + ..value = 'sub' + ..strings.addAll(['sub1', 'sub2'])); expect(top, expected); }); test('merges grandchild message', () { final empty = pb.Outer(); - final mergeMe1 = pb.Outer() - ..inner = (pb.Inner()..inner = (pb.Inner()..id = Int64(1))); - final mergeMe2 = pb.Outer() - ..inner = (pb.Inner()..inner = (pb.Inner()..value = 'new')); + final mergeMe1 = + pb.Outer()..inner = (pb.Inner()..inner = (pb.Inner()..id = Int64(1))); + final mergeMe2 = + pb.Outer()..inner = (pb.Inner()..inner = (pb.Inner()..value = 'new')); empty.mergeFromMessage(mergeMe1); empty.mergeFromMessage(mergeMe2); - final expected = pb.Outer() - ..inner = (pb.Inner() - ..inner = (pb.Inner() - ..id = Int64(1) - ..value = 'new')); + final expected = + pb.Outer() + ..inner = + (pb.Inner() + ..inner = + (pb.Inner() + ..id = Int64(1) + ..value = 'new')); expect(empty, expected); }); diff --git a/protoc_plugin/test/message_generator_test.dart b/protoc_plugin/test/message_generator_test.dart index 749c2b1cb..7bf696457 100644 --- a/protoc_plugin/test/message_generator_test.dart +++ b/protoc_plugin/test/message_generator_test.dart @@ -21,61 +21,65 @@ void main() { late DescriptorProto md; setUp(() async { fd = FileDescriptorProto(); - ed = EnumDescriptorProto() - ..name = 'PhoneType' - ..value.addAll([ - EnumValueDescriptorProto() - ..name = 'MOBILE' - ..number = 0, - EnumValueDescriptorProto() - ..name = 'HOME' - ..number = 1, - EnumValueDescriptorProto() - ..name = 'WORK' - ..number = 2, - EnumValueDescriptorProto() - ..name = 'BUSINESS' - ..number = 2 - ]); - md = DescriptorProto() - ..name = 'PhoneNumber' - ..field.addAll([ - // optional PhoneType type = 2 [default = HOME]; - FieldDescriptorProto() - ..name = 'type' - ..jsonName = 'type' - ..number = 2 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_ENUM - ..typeName = '.PhoneNumber.PhoneType', - // required string number = 1; - FieldDescriptorProto() - ..name = 'number' - ..jsonName = 'number' - ..number = 1 - ..label = FieldDescriptorProto_Label.LABEL_REQUIRED - ..type = FieldDescriptorProto_Type.TYPE_STRING, - FieldDescriptorProto() - ..name = 'name' - ..jsonName = 'name' - ..number = 3 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_STRING - ..defaultValue = r'$', - FieldDescriptorProto() - ..name = 'deprecated_field' - ..jsonName = 'deprecatedField' - ..number = 4 - ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL - ..type = FieldDescriptorProto_Type.TYPE_STRING - ..options = (FieldOptions()..deprecated = true), - ]) - ..enumType.add(ed); + ed = + EnumDescriptorProto() + ..name = 'PhoneType' + ..value.addAll([ + EnumValueDescriptorProto() + ..name = 'MOBILE' + ..number = 0, + EnumValueDescriptorProto() + ..name = 'HOME' + ..number = 1, + EnumValueDescriptorProto() + ..name = 'WORK' + ..number = 2, + EnumValueDescriptorProto() + ..name = 'BUSINESS' + ..number = 2, + ]); + md = + DescriptorProto() + ..name = 'PhoneNumber' + ..field.addAll([ + // optional PhoneType type = 2 [default = HOME]; + FieldDescriptorProto() + ..name = 'type' + ..jsonName = 'type' + ..number = 2 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_ENUM + ..typeName = '.PhoneNumber.PhoneType', + // required string number = 1; + FieldDescriptorProto() + ..name = 'number' + ..jsonName = 'number' + ..number = 1 + ..label = FieldDescriptorProto_Label.LABEL_REQUIRED + ..type = FieldDescriptorProto_Type.TYPE_STRING, + FieldDescriptorProto() + ..name = 'name' + ..jsonName = 'name' + ..number = 3 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_STRING + ..defaultValue = r'$', + FieldDescriptorProto() + ..name = 'deprecated_field' + ..jsonName = 'deprecatedField' + ..number = 4 + ..label = FieldDescriptorProto_Label.LABEL_OPTIONAL + ..type = FieldDescriptorProto_Type.TYPE_STRING + ..options = (FieldOptions()..deprecated = true), + ]) + ..enumType.add(ed); }); test('testMessageGenerator', () { - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); final mg = MessageGenerator.topLevel(md, fg, {}, null, {}, 0); @@ -88,19 +92,25 @@ void main() { mg.generate(writer); expectGolden(writer.toString(), 'messageGenerator.pb.dart'); expectGolden( - writer.sourceLocationInfo.toString(), 'messageGenerator.pb.dart.meta'); + writer.sourceLocationInfo.toString(), + 'messageGenerator.pb.dart.meta', + ); writer = IndentingWriter(filename: ''); mg.generateEnums(writer); expectGolden(writer.toString(), 'messageGeneratorEnums.pb.dart'); - expectGolden(writer.sourceLocationInfo.toString(), - 'messageGeneratorEnums.pb.dart.meta'); + expectGolden( + writer.sourceLocationInfo.toString(), + 'messageGeneratorEnums.pb.dart.meta', + ); }); test('testMetadataIndices', () { - final options = parseGenerationOptions( - CodeGeneratorRequest()..parameter = 'disable_constructor_args', - CodeGeneratorResponse())!; + final options = + parseGenerationOptions( + CodeGeneratorRequest()..parameter = 'disable_constructor_args', + CodeGeneratorResponse(), + )!; final fg = FileGenerator(fd, options); final mg = MessageGenerator.topLevel(md, fg, {}, null, {}, 0); @@ -113,7 +123,10 @@ void main() { final eq = ListEquality(); final fieldStringsMap = HashMap( - equals: eq.equals, hashCode: eq.hash, isValidKey: eq.isValidKey); + equals: eq.equals, + hashCode: eq.hash, + isValidKey: eq.isValidKey, + ); fieldStringsMap[[4, 0]] = ['PhoneNumber']; fieldStringsMap[[4, 0, 2, 0]] = ['type', 'hasType', 'clearType']; fieldStringsMap[[4, 0, 2, 1]] = ['number', 'hasNumber', 'clearNumber']; @@ -121,18 +134,22 @@ void main() { fieldStringsMap[[4, 0, 2, 3]] = [ 'deprecatedField', 'hasDeprecatedField', - 'clearDeprecatedField' + 'clearDeprecatedField', ]; final generatedContents = writer.toString(); final metadata = writer.sourceLocationInfo; for (final annotation in metadata.annotation) { - final annotatedName = - generatedContents.substring(annotation.begin, annotation.end); + final annotatedName = generatedContents.substring( + annotation.begin, + annotation.end, + ); final expectedStrings = fieldStringsMap[annotation.path]; if (expectedStrings == null) { - fail('The field path ${annotation.path} ' - 'did not match any expected field path.'); + fail( + 'The field path ${annotation.path} ' + 'did not match any expected field path.', + ); } expect(annotatedName, isIn(expectedStrings)); } diff --git a/protoc_plugin/test/message_set_test.dart b/protoc_plugin/test/message_set_test.dart index 40eebbc8a..350622f80 100644 --- a/protoc_plugin/test/message_set_test.dart +++ b/protoc_plugin/test/message_set_test.dart @@ -40,7 +40,7 @@ void main() { final encodedNested = [ 10, 44, 11, 16, 200, 166, 107, 26, 19, 8, 123, 18, 7, 116, 101, 115, // 116, 105, 110, 103, 26, 6, 40, 0, 40, 1, 40, 2, 12, 11, 16, 162, 233, // - 111, 26, 9, 40, 219, 7, 40, 142, 5, 40, 193, 2, 12 + 111, 26, 9, 40, 219, 7, 40, 142, 5, 40, 193, 2, 12, ]; // Example message with a top-level message set, encoded with the C++ @@ -60,13 +60,14 @@ void main() { // } final encodedTopLevel = [ 11, 16, 200, 166, 107, 26, 2, 8, 123, 12, 11, 16, 162, 233, 111, 26, 3, // - 40, 219, 7, 12 + 40, 219, 7, 12, ]; test('Parse message set extensions (nested)', () { - final registry = ExtensionRegistry() - ..add(TestMessage.ext1) - ..add(TestMessage.ext2); + final registry = + ExtensionRegistry() + ..add(TestMessage.ext1) + ..add(TestMessage.ext2); final msg = TestMessage.fromBuffer(encodedNested, registry); final ext1Value = @@ -83,9 +84,10 @@ void main() { }); test('Parse message set (top-level)', () { - final registry = ExtensionRegistry() - ..add(TestMessage.ext1) - ..add(TestMessage.ext2); + final registry = + ExtensionRegistry() + ..add(TestMessage.ext1) + ..add(TestMessage.ext2); final msg = MessageSet.fromBuffer(encodedTopLevel, registry); final ext1Value = msg.getExtension(TestMessage.ext1) as ExtensionMessage1; @@ -106,9 +108,10 @@ void main() { test('Reparse with extensions (nested message)', () { final msg = TestMessage.fromBuffer(encodedNested); - final registry = ExtensionRegistry() - ..add(TestMessage.ext1) - ..add(TestMessage.ext2); + final registry = + ExtensionRegistry() + ..add(TestMessage.ext1) + ..add(TestMessage.ext2); final reparsedInfo = registry.reparseMessage(msg.info); final ext1Value = @@ -125,9 +128,10 @@ void main() { test('Reparse with extensions (top-level message)', () { final msg = TestMessage.fromBuffer(encodedNested); - final registry = ExtensionRegistry() - ..add(TestMessage.ext1) - ..add(TestMessage.ext2); + final registry = + ExtensionRegistry() + ..add(TestMessage.ext1) + ..add(TestMessage.ext2); final reparsedMsg = registry.reparseMessage(msg); final ext1Value = @@ -178,17 +182,21 @@ void main() { final messageSetUnknownFields = UnknownFieldSet(); messageSetUnknownFields.addField( - 2, UnknownFieldSetField()..addVarint(Int64(987))); + 2, + UnknownFieldSetField()..addVarint(Int64(987)), + ); final messageSetEncoded = CodedBufferWriter(); messageSetUnknownFields.writeToCodedBufferWriter(messageSetEncoded); - final encoded = (Empty() - ..unknownFields.addField( - 123, - UnknownFieldSetField() - ..lengthDelimited.add(messageSetEncoded.toBuffer()))) - .writeToBuffer(); + final encoded = + (Empty() + ..unknownFields.addField( + 123, + UnknownFieldSetField() + ..lengthDelimited.add(messageSetEncoded.toBuffer()), + )) + .writeToBuffer(); final registry = ExtensionRegistry()..add(TestMessage.ext1); final msg = TestMessage.fromBuffer(encoded, registry); @@ -201,17 +209,21 @@ void main() { final messageSetUnknownFields = UnknownFieldSet(); messageSetUnknownFields.addField( - 2, UnknownFieldSetField()..addVarint(Int64(987))); + 2, + UnknownFieldSetField()..addVarint(Int64(987)), + ); final messageSetEncoded = CodedBufferWriter(); messageSetUnknownFields.writeToCodedBufferWriter(messageSetEncoded); - final encoded = (Empty() - ..unknownFields.addField( - 123, - UnknownFieldSetField() - ..lengthDelimited.add(messageSetEncoded.toBuffer()))) - .writeToBuffer(); + final encoded = + (Empty() + ..unknownFields.addField( + 123, + UnknownFieldSetField() + ..lengthDelimited.add(messageSetEncoded.toBuffer()), + )) + .writeToBuffer(); final registry = ExtensionRegistry()..add(TestMessage.ext1); final msg = TestMessage.fromBuffer(encoded, registry); @@ -219,10 +231,7 @@ void main() { }); } -enum Encoding { - lengthDelimited, - group, -} +enum Encoding { lengthDelimited, group } /// Generate a message set encoding with one extension. Extension will have /// extra tags. @@ -231,16 +240,20 @@ Uint8List encodeMessageSetWithExtraItemTags(Encoding encoding) { // Invalid field with tag 1. itemFieldGroup.addField( - 1, UnknownFieldSetField()..addLengthDelimited([1, 2, 3])); + 1, + UnknownFieldSetField()..addLengthDelimited([1, 2, 3]), + ); // Extension field. itemFieldGroup.addField( - 3, - UnknownFieldSetField() - ..addLengthDelimited((ExtensionMessage1() - ..a = 123456 - ..b = 'test') - .writeToBuffer())); + 3, + UnknownFieldSetField()..addLengthDelimited( + (ExtensionMessage1() + ..a = 123456 + ..b = 'test') + .writeToBuffer(), + ), + ); // Invalid field with tag 3. itemFieldGroup.addField(4, UnknownFieldSetField()..addVarint(Int64(123456))); @@ -256,16 +269,22 @@ Uint8List encodeMessageSetWithExtraItemTags(Encoding encoding) { final writer = CodedBufferWriter(); itemFieldGroup.writeToCodedBufferWriter(writer); messageSetUnknownFields.addField( - 1, UnknownFieldSetField()..addLengthDelimited(writer.toBuffer())); + 1, + UnknownFieldSetField()..addLengthDelimited(writer.toBuffer()), + ); break; case Encoding.group: messageSetUnknownFields.addField( - 1, UnknownFieldSetField()..addGroup(itemFieldGroup)); + 1, + UnknownFieldSetField()..addGroup(itemFieldGroup), + ); break; } messageSetUnknownFields.addField( - 1, UnknownFieldSetField()..addGroup(itemFieldGroup)); + 1, + UnknownFieldSetField()..addGroup(itemFieldGroup), + ); final messageSetEncoded = CodedBufferWriter(); messageSetUnknownFields.writeToCodedBufferWriter(messageSetEncoded); diff --git a/protoc_plugin/test/message_test.dart b/protoc_plugin/test/message_test.dart index 30ab05d06..cfbbe104d 100644 --- a/protoc_plugin/test/message_test.dart +++ b/protoc_plugin/test/message_test.dart @@ -15,26 +15,29 @@ import 'src/test_util.dart'; void main() { final testRequiredUninitialized = TestRequired(); - final testRequiredInitialized = TestRequired() - ..a = 1 - ..b = 2 - ..c = 3; + final testRequiredInitialized = + TestRequired() + ..a = 1 + ..b = 2 + ..c = 3; test('testMergeFrom', () { - final mergeSource = TestAllTypes() - ..optionalInt32 = 1 - ..optionalString = 'foo' - ..optionalForeignMessage = ForeignMessage() - ..optionalNestedMessage = (TestAllTypes_NestedMessage()..i = 42) - ..repeatedString.add('bar'); - - final mergeDest = TestAllTypes() - ..optionalInt64 = make64(2) - ..optionalString = 'baz' - ..optionalForeignMessage = ForeignMessage() - ..optionalForeignMessage = (ForeignMessage()..c = 3) - ..optionalNestedMessage = (TestAllTypes_NestedMessage()..bb = 43) - ..repeatedString.add('qux'); + final mergeSource = + TestAllTypes() + ..optionalInt32 = 1 + ..optionalString = 'foo' + ..optionalForeignMessage = ForeignMessage() + ..optionalNestedMessage = (TestAllTypes_NestedMessage()..i = 42) + ..repeatedString.add('bar'); + + final mergeDest = + TestAllTypes() + ..optionalInt64 = make64(2) + ..optionalString = 'baz' + ..optionalForeignMessage = ForeignMessage() + ..optionalForeignMessage = (ForeignMessage()..c = 3) + ..optionalNestedMessage = (TestAllTypes_NestedMessage()..bb = 43) + ..repeatedString.add('qux'); final mergeResultExpected = ''' optionalInt32: 1 @@ -51,9 +54,10 @@ repeatedString: bar repeatedString: qux '''; - final result = TestAllTypes() - ..mergeFromMessage(mergeSource) - ..mergeFromMessage(mergeDest); + final result = + TestAllTypes() + ..mergeFromMessage(mergeSource) + ..mergeFromMessage(mergeDest); expect(result.toString(), mergeResultExpected); }); @@ -63,11 +67,17 @@ repeatedString: qux expect(message.isInitialized(), isFalse, reason: 'no required fields set'); message.a = 1; - expect(message.isInitialized(), isFalse, - reason: 'single required field set'); + expect( + message.isInitialized(), + isFalse, + reason: 'single required field set', + ); message.b = 1; - expect(message.isInitialized(), isFalse, - reason: 'all but one required field set'); + expect( + message.isInitialized(), + isFalse, + reason: 'all but one required field set', + ); message.c = 1; expect(message.isInitialized(), isTrue, reason: 'required fields set'); }); diff --git a/protoc_plugin/test/names_test.dart b/protoc_plugin/test/names_test.dart index c664f2911..17f7fc986 100644 --- a/protoc_plugin/test/names_test.dart +++ b/protoc_plugin/test/names_test.dart @@ -14,7 +14,7 @@ Matcher throwsMessage(String msg) => throwsA(_ToStringMatcher(equals(msg))); class _ToStringMatcher extends CustomMatcher { _ToStringMatcher(Matcher matcher) - : super('object where toString() returns', 'toString()', matcher); + : super('object where toString() returns', 'toString()', matcher); @override String featureValueOf(dynamic actual) => actual.toString(); } @@ -53,39 +53,54 @@ void main() { }); test('Throws exception for dart_name option containing a space', () { - final descriptor = DescriptorProto() - ..name = 'Example' - ..field.add(stringField('first', 1, 'hello world')); - expect(() { - names.messageMemberNames(descriptor, '', {}); - }, - throwsMessage('Example.first: dart_name option is invalid: ' - "'hello world' is not a valid Dart field name")); + final descriptor = + DescriptorProto() + ..name = 'Example' + ..field.add(stringField('first', 1, 'hello world')); + expect( + () { + names.messageMemberNames(descriptor, '', {}); + }, + throwsMessage( + 'Example.first: dart_name option is invalid: ' + "'hello world' is not a valid Dart field name", + ), + ); }); test('Throws exception for dart_name option set to reserved word', () { - final descriptor = DescriptorProto() - ..name = 'Example' - ..field.add(stringField('first', 1, 'class')); - expect(() { - names.messageMemberNames(descriptor, '', {}); - }, - throwsMessage('Example.first: ' - "dart_name option is invalid: 'class' is already used")); + final descriptor = + DescriptorProto() + ..name = 'Example' + ..field.add(stringField('first', 1, 'class')); + expect( + () { + names.messageMemberNames(descriptor, '', {}); + }, + throwsMessage( + 'Example.first: ' + "dart_name option is invalid: 'class' is already used", + ), + ); }); test('Throws exception for duplicate dart_name options', () { - final descriptor = DescriptorProto() - ..name = 'Example' - ..field.addAll([ - stringField('first', 1, 'renamed'), - stringField('second', 2, 'renamed'), - ]); - expect(() { - names.messageMemberNames(descriptor, '', {}); - }, - throwsMessage('Example.second: ' - "dart_name option is invalid: 'renamed' is already used")); + final descriptor = + DescriptorProto() + ..name = 'Example' + ..field.addAll([ + stringField('first', 1, 'renamed'), + stringField('second', 2, 'renamed'), + ]); + expect( + () { + names.messageMemberNames(descriptor, '', {}); + }, + throwsMessage( + 'Example.second: ' + "dart_name option is invalid: 'renamed' is already used", + ), + ); }); test('message classes renamed to avoid Function keyword', () { @@ -121,9 +136,14 @@ void main() { final used = {'a_foo', 'b_foo_one'}; expect( - names.disambiguateName('foo', used, oneTwoThree(), - generateVariants: variants), - 'foo_two'); + names.disambiguateName( + 'foo', + used, + oneTwoThree(), + generateVariants: variants, + ), + 'foo_two', + ); expect(used, {'a_foo', 'b_foo_one', 'a_foo_two', 'b_foo_two'}); } }); @@ -145,20 +165,29 @@ void main() { }); test('defaultSuffixes', () { - expect(names.defaultSuffixes().take(5).toList(), - ['_', '_0', '_1', '_2', '_3']); + expect(names.defaultSuffixes().take(5).toList(), [ + '_', + '_0', + '_1', + '_2', + '_3', + ]); }); test('oneof names no disambiguation', () { final oneofDescriptor = oneofField('foo'); - final descriptor = DescriptorProto() - ..name = 'Parent' - ..field.addAll([stringFieldOneof('first', 1, 0)]) - ..oneofDecl.add(oneofDescriptor); + final descriptor = + DescriptorProto() + ..name = 'Parent' + ..field.addAll([stringFieldOneof('first', 1, 0)]) + ..oneofDecl.add(oneofDescriptor); final usedTopLevelNames = {}; - final memberNames = - names.messageMemberNames(descriptor, 'Parent', usedTopLevelNames); + final memberNames = names.messageMemberNames( + descriptor, + 'Parent', + usedTopLevelNames, + ); expect(usedTopLevelNames.length, 1); expect(usedTopLevelNames, {'Parent_Foo'}); @@ -174,15 +203,19 @@ void main() { test('oneof names disambiguate method names', () { final oneofDescriptor = oneofField('foo'); - final descriptor = DescriptorProto() - ..name = 'Parent' - ..field.addAll([stringFieldOneof('first', 1, 0)]) - ..oneofDecl.add(oneofDescriptor); + final descriptor = + DescriptorProto() + ..name = 'Parent' + ..field.addAll([stringFieldOneof('first', 1, 0)]) + ..oneofDecl.add(oneofDescriptor); final usedTopLevelNames = {}; final memberNames = names.messageMemberNames( - descriptor, 'Parent', usedTopLevelNames, - reserved: ['clearFoo']); + descriptor, + 'Parent', + usedTopLevelNames, + reserved: ['clearFoo'], + ); expect(usedTopLevelNames.length, 1); expect(usedTopLevelNames, {'Parent_Foo'}); @@ -198,14 +231,18 @@ void main() { test('oneof names disambiguate top level name', () { final oneofDescriptor = oneofField('foo'); - final descriptor = DescriptorProto() - ..name = 'Parent' - ..field.addAll([stringFieldOneof('first', 1, 0)]) - ..oneofDecl.add(oneofDescriptor); + final descriptor = + DescriptorProto() + ..name = 'Parent' + ..field.addAll([stringFieldOneof('first', 1, 0)]) + ..oneofDecl.add(oneofDescriptor); final usedTopLevelNames = {'Parent_Foo'}; - final memberNames = - names.messageMemberNames(descriptor, 'Parent', usedTopLevelNames); + final memberNames = names.messageMemberNames( + descriptor, + 'Parent', + usedTopLevelNames, + ); expect(usedTopLevelNames.length, 2); expect(usedTopLevelNames, {'Parent_Foo', 'Parent_Foo_'}); @@ -224,8 +261,10 @@ void main() { }); test('The proto name is set correctly', () { - expect(json_name.JsonNamedMessage().info_.byName['barName']!.protoName, - 'foo_name'); + expect( + json_name.JsonNamedMessage().info_.byName['barName']!.protoName, + 'foo_name', + ); }); test('Invalid characters are escaped from json_name', () { diff --git a/protoc_plugin/test/omit_enum_names_test.dart b/protoc_plugin/test/omit_enum_names_test.dart index 4bc927e9c..269648611 100644 --- a/protoc_plugin/test/omit_enum_names_test.dart +++ b/protoc_plugin/test/omit_enum_names_test.dart @@ -12,15 +12,17 @@ String constant() => 'SHOULD_BE_PRESENT'; Future main() async { test('enum name available depending on environment', () { expect( - ForeignEnum.FOREIGN_FOO.name, - const bool.fromEnvironment('protobuf.omit_enum_names') - ? '' - : 'FOREIGN_FOO'); + ForeignEnum.FOREIGN_FOO.name, + const bool.fromEnvironment('protobuf.omit_enum_names') + ? '' + : 'FOREIGN_FOO', + ); expect( - ForeignEnum.FOREIGN_FOO.toString(), - const bool.fromEnvironment('protobuf.omit_enum_names') - ? '4' - : 'FOREIGN_FOO'); + 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 ce1d4d598..a8f3a90ec 100644 --- a/protoc_plugin/test/omit_field_names_test.dart +++ b/protoc_plugin/test/omit_field_names_test.dart @@ -14,10 +14,11 @@ Future main() async { final proto = TestAllTypes()..optionalForeignMessage = ForeignMessage(); expect( - proto.toString(), - const bool.fromEnvironment('protobuf.omit_field_names') - ? '19: {\n}\n' - : 'optionalForeignMessage: {\n}\n'); + proto.toString(), + const bool.fromEnvironment('protobuf.omit_field_names') + ? '19: {\n}\n' + : 'optionalForeignMessage: {\n}\n', + ); expect(constant(), 'SHOULD_BE_PRESENT'); }); } diff --git a/protoc_plugin/test/omit_message_names_test.dart b/protoc_plugin/test/omit_message_names_test.dart index 9703e4463..0751d5c56 100644 --- a/protoc_plugin/test/omit_message_names_test.dart +++ b/protoc_plugin/test/omit_message_names_test.dart @@ -12,10 +12,11 @@ String constant() => 'SHOULD_BE_PRESENT'; Future main() async { test('message name available depending on environment', () { expect( - TestAllTypes_NestedMessage().info_.qualifiedMessageName, - const bool.fromEnvironment('protobuf.omit_message_names') - ? '' - : 'protobuf_unittest.TestAllTypes.NestedMessage'); + TestAllTypes_NestedMessage().info_.qualifiedMessageName, + const bool.fromEnvironment('protobuf.omit_message_names') + ? '' + : 'protobuf_unittest.TestAllTypes.NestedMessage', + ); expect(constant(), 'SHOULD_BE_PRESENT'); }); } diff --git a/protoc_plugin/test/proto3_json_test.dart b/protoc_plugin/test/proto3_json_test.dart index da2772bfb..e421bbea9 100644 --- a/protoc_plugin/test/proto3_json_test.dart +++ b/protoc_plugin/test/proto3_json_test.dart @@ -68,19 +68,19 @@ final testAllTypesJson = { 'repeatedBytes': ['MjE2', 'MzE2'], 'repeatedgroup': [ {'a': 217}, - {'a': 317} + {'a': 317}, ], 'repeatedNestedMessage': [ {'bb': 218}, - {'bb': 318} + {'bb': 318}, ], 'repeatedForeignMessage': [ {'c': 219}, - {'c': 319} + {'c': 319}, ], 'repeatedImportMessage': [ {'d': 220}, - {'d': 320} + {'d': 320}, ], 'repeatedNestedEnum': ['BAR', 'BAZ'], 'repeatedForeignEnum': ['FOREIGN_BAR', 'FOREIGN_BAZ'], @@ -106,28 +106,32 @@ final testAllTypesJson = { 'defaultForeignEnum': 'FOREIGN_FOO', 'defaultImportEnum': 'IMPORT_FOO', 'defaultStringPiece': '424', - 'defaultCord': '425' + 'defaultCord': '425', }; void main() { test('toProto3Json works', () { - final proto = TopEntity() - ..id = Int64(1) - ..stringValue = 'foo' - ..strings.addAll(['test', 'repeated', 'field']) - ..anyValue = Any.pack(SubEntity() - ..id = Int64(4) - ..anyValue = Any.pack(SubSubEntity()..id = Int64(5))) - ..sub = (SubEntity() - ..id = Int64(2) - ..subSub = (SubSubEntity()..id = Int64(3))); + final proto = + TopEntity() + ..id = Int64(1) + ..stringValue = 'foo' + ..strings.addAll(['test', 'repeated', 'field']) + ..anyValue = Any.pack( + SubEntity() + ..id = Int64(4) + ..anyValue = Any.pack(SubSubEntity()..id = Int64(5)), + ) + ..sub = + (SubEntity() + ..id = Int64(2) + ..subSub = (SubSubEntity()..id = Int64(3))); final typeRegistry = TypeRegistry([SubEntity(), SubSubEntity()]); final json = proto.toProto3Json(typeRegistry: typeRegistry); expect( - proto == - (TopEntity() - ..mergeFromProto3Json(json, typeRegistry: typeRegistry)), - true); + proto == + (TopEntity()..mergeFromProto3Json(json, typeRegistry: typeRegistry)), + true, + ); }); group('encode', () { @@ -147,17 +151,20 @@ void main() { expect(message.toProto3Json(), { 'optionalUint64': '17293822573397606400', - 'optionalFixed64': '-1152921500311945215' + 'optionalFixed64': '-1152921500311945215', }); }); test('doubles', () { void testValue(double value, Object expected) { - final message = TestAllTypes() - ..defaultFloat = value - ..defaultDouble = value; + final message = + TestAllTypes() + ..defaultFloat = value + ..defaultDouble = value; expect( - (message.toProto3Json() as Map)['defaultDouble'], equals(expected)); + (message.toProto3Json() as Map)['defaultDouble'], + equals(expected), + ); } testValue(-0.0, -0.0); @@ -170,30 +177,32 @@ void main() { }); test('map value', () { - final message = TestMap() - ..int32ToInt32Field[32] = 32 - ..int32ToStringField[0] = 'foo' - ..int32ToStringField[1] = 'bar' - ..int32ToBytesField[-1] = [1, 2, 3] - ..int32ToEnumField[1] = TestMap_EnumValue.BAZ - ..int32ToMessageField[21] = (TestMap_MessageValue() - ..value = 2 - ..secondValue = 3) - ..stringToInt32Field['key'] = -1 - ..uint32ToInt32Field[0] = 0 - ..int64ToInt32Field[Int64.ZERO] = 0 - ..int64ToInt32Field[Int64.ONE] = 1 - ..int64ToInt32Field[-Int64.ONE] = -1 - ..int64ToInt32Field[Int64.MIN_VALUE] = -2 - ..int64ToInt32Field[Int64.MAX_VALUE] = 2 - ..uint64ToInt32Field[Int64.MIN_VALUE] = -2; + final message = + TestMap() + ..int32ToInt32Field[32] = 32 + ..int32ToStringField[0] = 'foo' + ..int32ToStringField[1] = 'bar' + ..int32ToBytesField[-1] = [1, 2, 3] + ..int32ToEnumField[1] = TestMap_EnumValue.BAZ + ..int32ToMessageField[21] = + (TestMap_MessageValue() + ..value = 2 + ..secondValue = 3) + ..stringToInt32Field['key'] = -1 + ..uint32ToInt32Field[0] = 0 + ..int64ToInt32Field[Int64.ZERO] = 0 + ..int64ToInt32Field[Int64.ONE] = 1 + ..int64ToInt32Field[-Int64.ONE] = -1 + ..int64ToInt32Field[Int64.MIN_VALUE] = -2 + ..int64ToInt32Field[Int64.MAX_VALUE] = 2 + ..uint64ToInt32Field[Int64.MIN_VALUE] = -2; expect(message.toProto3Json(), { 'int32ToInt32Field': {'32': 32}, 'int32ToStringField': {'0': 'foo', '1': 'bar'}, 'int32ToBytesField': {'-1': 'AQID'}, 'int32ToEnumField': {'1': 'BAZ'}, 'int32ToMessageField': { - '21': {'value': 2, 'secondValue': 3} + '21': {'value': 2, 'secondValue': 3}, }, 'stringToInt32Field': {'key': -1}, 'uint32ToInt32Field': {'0': 0}, @@ -202,7 +211,7 @@ void main() { '1': 1, '-1': -1, '-9223372036854775808': -2, - '9223372036854775807': 2 + '9223372036854775807': 2, }, 'uint64ToInt32Field': {'9223372036854775808': -2}, }); @@ -210,132 +219,176 @@ void main() { test('Timestamp', () { expect( - Timestamp.fromDateTime(DateTime.utc(1969, 7, 20, 20, 17, 40)) - .toProto3Json(), - '1969-07-20T20:17:40Z'); - expect(Timestamp.fromDateTime(DateTime.utc(9)).toProto3Json(), - '0009-01-01T00:00:00Z'); - expect(Timestamp.fromDateTime(DateTime.utc(420)).toProto3Json(), - '0420-01-01T00:00:00Z'); - expect(() => Timestamp.fromDateTime(DateTime.utc(42001)).toProto3Json(), - throwsA(TypeMatcher())); - expect(() => Timestamp.fromDateTime(DateTime.utc(-1)).toProto3Json(), - throwsA(TypeMatcher())); - expect( - Timestamp.fromDateTime(DateTime.utc(9999, 12, 31, 23, 59, 59)) - .toProto3Json(), - '9999-12-31T23:59:59Z'); - - expect((Timestamp()..nanos = 1).toProto3Json(), - '1970-01-01T00:00:00.000000001Z'); - expect((Timestamp()..nanos = 8200000).toProto3Json(), - '1970-01-01T00:00:00.008200Z'); - expect(() => (Timestamp()..nanos = -8200000).toProto3Json(), - throwsA(TypeMatcher())); - expect(() => (Timestamp()..nanos = -8200000).toProto3Json(), - throwsA(TypeMatcher())); - expect(() => (Timestamp()..nanos = 1000000000).toProto3Json(), - throwsA(TypeMatcher())); + Timestamp.fromDateTime( + DateTime.utc(1969, 7, 20, 20, 17, 40), + ).toProto3Json(), + '1969-07-20T20:17:40Z', + ); + expect( + Timestamp.fromDateTime(DateTime.utc(9)).toProto3Json(), + '0009-01-01T00:00:00Z', + ); + expect( + Timestamp.fromDateTime(DateTime.utc(420)).toProto3Json(), + '0420-01-01T00:00:00Z', + ); + expect( + () => Timestamp.fromDateTime(DateTime.utc(42001)).toProto3Json(), + throwsA(TypeMatcher()), + ); + expect( + () => Timestamp.fromDateTime(DateTime.utc(-1)).toProto3Json(), + throwsA(TypeMatcher()), + ); + expect( + Timestamp.fromDateTime( + DateTime.utc(9999, 12, 31, 23, 59, 59), + ).toProto3Json(), + '9999-12-31T23:59:59Z', + ); + + expect( + (Timestamp()..nanos = 1).toProto3Json(), + '1970-01-01T00:00:00.000000001Z', + ); + expect( + (Timestamp()..nanos = 8200000).toProto3Json(), + '1970-01-01T00:00:00.008200Z', + ); + expect( + () => (Timestamp()..nanos = -8200000).toProto3Json(), + throwsA(TypeMatcher()), + ); + expect( + () => (Timestamp()..nanos = -8200000).toProto3Json(), + throwsA(TypeMatcher()), + ); + expect( + () => (Timestamp()..nanos = 1000000000).toProto3Json(), + throwsA(TypeMatcher()), + ); }); test('Duration', () { expect( - (Duration() - ..seconds = Int64(0) - ..nanos = 0) - .toProto3Json(), - '0s'); - expect( - (Duration() - ..seconds = Int64(10) - ..nanos = 0) - .toProto3Json(), - '10s'); - expect( - (Duration() - ..seconds = Int64(10) - ..nanos = 1) - .toProto3Json(), - '10.000000001s'); - expect( - (Duration() - ..seconds = Int64(10) - ..nanos = 10) - .toProto3Json(), - '10.00000001s'); - expect( - (Duration() - ..seconds = -Int64(1) - ..nanos = -99000) - .toProto3Json(), - '-1.000099s'); + (Duration() + ..seconds = Int64(0) + ..nanos = 0) + .toProto3Json(), + '0s', + ); + expect( + (Duration() + ..seconds = Int64(10) + ..nanos = 0) + .toProto3Json(), + '10s', + ); + expect( + (Duration() + ..seconds = Int64(10) + ..nanos = 1) + .toProto3Json(), + '10.000000001s', + ); + expect( + (Duration() + ..seconds = Int64(10) + ..nanos = 10) + .toProto3Json(), + '10.00000001s', + ); + expect( + (Duration() + ..seconds = -Int64(1) + ..nanos = -99000) + .toProto3Json(), + '-1.000099s', + ); }); test('Any', () { expect( - Any.pack(TestAllTypes()..optionalFixed64 = Int64(100)) - .toProto3Json(typeRegistry: TypeRegistry([TestAllTypes()])), - { - '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', - 'optionalFixed64': '100' - }); - expect( - Any.pack(Timestamp.fromDateTime(DateTime.utc(1969, 7, 20, 20, 17))) - .toProto3Json(typeRegistry: TypeRegistry([Timestamp()])), - { - '@type': 'type.googleapis.com/google.protobuf.Timestamp', - 'value': '1969-07-20T20:17:00Z' - }); + Any.pack( + TestAllTypes()..optionalFixed64 = Int64(100), + ).toProto3Json(typeRegistry: TypeRegistry([TestAllTypes()])), + { + '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', + 'optionalFixed64': '100', + }, + ); expect( - () => Any.pack(Timestamp.fromDateTime(DateTime(1969, 7, 20, 20, 17))) - .toProto3Json(), - throwsA(TypeMatcher())); + Any.pack( + Timestamp.fromDateTime(DateTime.utc(1969, 7, 20, 20, 17)), + ).toProto3Json(typeRegistry: TypeRegistry([Timestamp()])), + { + '@type': 'type.googleapis.com/google.protobuf.Timestamp', + 'value': '1969-07-20T20:17:00Z', + }, + ); + expect( + () => + Any.pack( + Timestamp.fromDateTime(DateTime(1969, 7, 20, 20, 17)), + ).toProto3Json(), + throwsA(TypeMatcher()), + ); }); test('Nested Any', () { final packedOne = Any.pack(AnyMessage1()..value = '1'); - final packedTwo = Any.pack(AnyMessage2() - ..value = '2' - ..anyField2 = packedOne); - expect( - packedTwo.toProto3Json( - typeRegistry: TypeRegistry([AnyMessage1(), AnyMessage2()])), - { - 'anyField2': { - 'value': '1', - '@type': 'type.googleapis.com/nested_any.AnyMessage1' - }, - 'value': '2', - '@type': 'type.googleapis.com/nested_any.AnyMessage2' - }); + final packedTwo = Any.pack( + AnyMessage2() + ..value = '2' + ..anyField2 = packedOne, + ); + expect( + packedTwo.toProto3Json( + typeRegistry: TypeRegistry([AnyMessage1(), AnyMessage2()]), + ), + { + 'anyField2': { + 'value': '1', + '@type': 'type.googleapis.com/nested_any.AnyMessage1', + }, + 'value': '2', + '@type': 'type.googleapis.com/nested_any.AnyMessage2', + }, + ); }); test('struct', () { - final s = Struct() - ..fields['null'] = (Value()..nullValue = NullValue.NULL_VALUE) - ..fields['number'] = (Value()..numberValue = 22.3) - ..fields['string'] = (Value()..stringValue = 'foo') - ..fields['bool'] = (Value()..boolValue = false) - ..fields['struct'] = (Value() - ..structValue = - (Struct()..fields['a'] = (Value()..numberValue = 0.0))) - ..fields['list'] = (Value() - ..listValue = (ListValue() - ..values.addAll([ - Value()..structValue = Struct(), - Value()..listValue = ListValue(), - Value()..stringValue = 'why' - ]))); + final s = + Struct() + ..fields['null'] = (Value()..nullValue = NullValue.NULL_VALUE) + ..fields['number'] = (Value()..numberValue = 22.3) + ..fields['string'] = (Value()..stringValue = 'foo') + ..fields['bool'] = (Value()..boolValue = false) + ..fields['struct'] = + (Value() + ..structValue = + (Struct()..fields['a'] = (Value()..numberValue = 0.0))) + ..fields['list'] = + (Value() + ..listValue = + (ListValue() + ..values.addAll([ + Value()..structValue = Struct(), + Value()..listValue = ListValue(), + Value()..stringValue = 'why', + ]))); expect(s.toProto3Json(), { 'null': null, 'number': 22.3, 'string': 'foo', 'bool': false, 'struct': {'a': 0}, - 'list': [{}, [], 'why'] + 'list': [{}, [], 'why'], }); expect( - () => Value().toProto3Json(), throwsA(TypeMatcher())); + () => Value().toProto3Json(), + throwsA(TypeMatcher()), + ); }); test('empty', () { @@ -343,16 +396,17 @@ void main() { }); test('wrapper types', () { - final t = TestWellKnownTypes() - ..doubleField = (DoubleValue()..value = 10.01) - ..floatField = (FloatValue()..value = 3.0) - ..int64Field = (Int64Value()..value = Int64.MIN_VALUE) - ..uint64Field = (UInt64Value()..value = Int64.MIN_VALUE) - ..int32Field = (Int32Value()..value = 101) - ..uint32Field = (UInt32Value()..value = 102) - ..boolField = (BoolValue()..value = false) - ..stringField = (StringValue()..value = 'Pop') - ..bytesField = (BytesValue()..value = [8, 9, 10]); + final t = + TestWellKnownTypes() + ..doubleField = (DoubleValue()..value = 10.01) + ..floatField = (FloatValue()..value = 3.0) + ..int64Field = (Int64Value()..value = Int64.MIN_VALUE) + ..uint64Field = (UInt64Value()..value = Int64.MIN_VALUE) + ..int32Field = (Int32Value()..value = 101) + ..uint32Field = (UInt32Value()..value = 102) + ..boolField = (BoolValue()..value = false) + ..stringField = (StringValue()..value = 'Pop') + ..bytesField = (BytesValue()..value = [8, 9, 10]); expect(t.toProto3Json(), { 'doubleField': 10.01, 'floatField': 3, @@ -368,40 +422,52 @@ void main() { test('field mask', () { expect(FieldMask().toProto3Json(), ''); - expect((FieldMask()..paths.addAll(['foo_bar_baz'])).toProto3Json(), - 'fooBarBaz'); - expect((FieldMask()..paths.addAll(['foo_bar', 'zop'])).toProto3Json(), - 'fooBar,zop'); - expect(() => (FieldMask()..paths.add('foo_3_bar')).toProto3Json(), - throwsA(TypeMatcher())); - expect(() => (FieldMask()..paths.add('foo__bar')).toProto3Json(), - throwsA(TypeMatcher())); - expect(() => (FieldMask()..paths.add('fooBar')).toProto3Json(), - throwsA(TypeMatcher())); + expect( + (FieldMask()..paths.addAll(['foo_bar_baz'])).toProto3Json(), + 'fooBarBaz', + ); + expect( + (FieldMask()..paths.addAll(['foo_bar', 'zop'])).toProto3Json(), + 'fooBar,zop', + ); + expect( + () => (FieldMask()..paths.add('foo_3_bar')).toProto3Json(), + throwsA(TypeMatcher()), + ); + expect( + () => (FieldMask()..paths.add('foo__bar')).toProto3Json(), + throwsA(TypeMatcher()), + ); + expect( + () => (FieldMask()..paths.add('fooBar')).toProto3Json(), + throwsA(TypeMatcher()), + ); }); }); group('decode', () { - Matcher parseFailure(List expectedPath) => throwsA(predicate((e) { - if (e is FormatException) { - final pathExpression = - RegExp(r'root(\["[^"]*"]*\])*').firstMatch(e.message)![0]!; - final actualPath = RegExp(r'\["([^"]*)"\]') - .allMatches(pathExpression) - .map((match) => match[1]) - .toList(); - if (actualPath.length != expectedPath.length) return false; - for (var i = 0; i < actualPath.length; i++) { - if (actualPath[i] != expectedPath[i]) return false; - } - return true; + Matcher parseFailure(List expectedPath) => throwsA( + predicate((e) { + if (e is FormatException) { + final pathExpression = + RegExp(r'root(\["[^"]*"]*\])*').firstMatch(e.message)![0]!; + final actualPath = + RegExp( + r'\["([^"]*)"\]', + ).allMatches(pathExpression).map((match) => match[1]).toList(); + if (actualPath.length != expectedPath.length) return false; + for (var i = 0; i < actualPath.length; i++) { + if (actualPath[i] != expectedPath[i]) return false; } - return false; - })); + return true; + } + return false; + }), + ); test('Nulls', () { - final decoded = TestAllTypes() - ..mergeFromProto3Json({'defaultString': null}); + final decoded = + TestAllTypes()..mergeFromProto3Json({'defaultString': null}); expect(decoded, TestAllTypes()); }); test('decode TestAllTypes', () { @@ -410,428 +476,585 @@ void main() { }); test('Type expectations', () { expect( - () => TestAllTypes()..mergeFromProto3Json({1: 1}), parseFailure([])); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalBool': 1}), - parseFailure(['optionalBool'])); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalBytes': 1}), - parseFailure(['optionalBytes'])); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalBytes': '()'}), - parseFailure(['optionalBytes'])); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalInt32': '()'}), - parseFailure(['optionalInt32'])); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalInt32': 20.4}), - parseFailure(['optionalInt32'])); - expect(TestAllTypes()..mergeFromProto3Json({'optionalInt32': '28'}), - TestAllTypes()..optionalInt32 = 28); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalInt64': '()'}), - parseFailure(['optionalInt64'])); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalInt64': 20.4}), - parseFailure(['optionalInt64'])); - expect(TestAllTypes()..mergeFromProto3Json({'optionalInt64': '28'}), - TestAllTypes()..optionalInt64 = Int64(28)); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalDouble': 'a'}), - parseFailure(['optionalDouble'])); - expect(TestAllTypes()..mergeFromProto3Json({'optionalDouble': 28}), - TestAllTypes()..optionalDouble = 28.0); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalDouble': 'a'}), - parseFailure(['optionalDouble'])); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalString': 11}), - parseFailure(['optionalString'])); - expect( - () => TestAllTypes() - ..mergeFromProto3Json({'optionalEnum': 'wrongValue'}), - parseFailure(['optionalEnum'])); - expect(() => TestAllTypes()..mergeFromProto3Json({'optionalEnum': []}), - parseFailure(['optionalEnum'])); - expect( - () => - TestAllTypes()..mergeFromProto3Json({'optionalNestedEnum': 100}), - parseFailure(['optionalNestedEnum'])); - expect( - TestAllTypes()..mergeFromProto3Json({'optionalNestedEnum': 1}), - TestAllTypes() - ..optionalNestedEnum = TestAllTypes_NestedEnum.valueOf(1)!); - expect(TestAllTypes()..mergeFromProto3Json({'repeatedBool': null}), - TestAllTypes()); - expect(() => TestAllTypes()..mergeFromProto3Json({'repeatedBool': 100}), - parseFailure(['repeatedBool'])); - expect( - () => TestAllTypes() - ..mergeFromProto3Json({ - 'repeatedBool': [true, false, 1] + () => TestAllTypes()..mergeFromProto3Json({1: 1}), + parseFailure([]), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalBool': 1}), + parseFailure(['optionalBool']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalBytes': 1}), + parseFailure(['optionalBytes']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalBytes': '()'}), + parseFailure(['optionalBytes']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalInt32': '()'}), + parseFailure(['optionalInt32']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalInt32': 20.4}), + parseFailure(['optionalInt32']), + ); + expect( + TestAllTypes()..mergeFromProto3Json({'optionalInt32': '28'}), + TestAllTypes()..optionalInt32 = 28, + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalInt64': '()'}), + parseFailure(['optionalInt64']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalInt64': 20.4}), + parseFailure(['optionalInt64']), + ); + expect( + TestAllTypes()..mergeFromProto3Json({'optionalInt64': '28'}), + TestAllTypes()..optionalInt64 = Int64(28), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalDouble': 'a'}), + parseFailure(['optionalDouble']), + ); + expect( + TestAllTypes()..mergeFromProto3Json({'optionalDouble': 28}), + TestAllTypes()..optionalDouble = 28.0, + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalDouble': 'a'}), + parseFailure(['optionalDouble']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalString': 11}), + parseFailure(['optionalString']), + ); + expect( + () => + TestAllTypes()..mergeFromProto3Json({'optionalEnum': 'wrongValue'}), + parseFailure(['optionalEnum']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalEnum': []}), + parseFailure(['optionalEnum']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'optionalNestedEnum': 100}), + parseFailure(['optionalNestedEnum']), + ); + expect( + TestAllTypes()..mergeFromProto3Json({'optionalNestedEnum': 1}), + TestAllTypes() + ..optionalNestedEnum = TestAllTypes_NestedEnum.valueOf(1)!, + ); + expect( + TestAllTypes()..mergeFromProto3Json({'repeatedBool': null}), + TestAllTypes(), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json({'repeatedBool': 100}), + parseFailure(['repeatedBool']), + ); + expect( + () => + TestAllTypes()..mergeFromProto3Json({ + 'repeatedBool': [true, false, 1], }), - parseFailure(['repeatedBool', '2'])); - expect(() => TestAllTypes()..mergeFromProto3Json(Object()), - parseFailure([])); + parseFailure(['repeatedBool', '2']), + ); + expect( + () => TestAllTypes()..mergeFromProto3Json(Object()), + parseFailure([]), + ); }); test('merging behavior', () { - final t = TestAllTypes() - ..optionalForeignMessage = ForeignMessage() - ..repeatedForeignMessage.add(ForeignMessage()..c = 1); + final t = + TestAllTypes() + ..optionalForeignMessage = ForeignMessage() + ..repeatedForeignMessage.add(ForeignMessage()..c = 1); final f = t.optionalForeignMessage; expect( - t - ..mergeFromProto3Json({ - 'repeatedForeignMessage': [ - {'c': 2} - ], - 'optionalForeignMessage': {'c': 2} - }), - TestAllTypes() - ..optionalForeignMessage = (ForeignMessage()..c = 2) - ..repeatedForeignMessage - .addAll([ForeignMessage()..c = 1, ForeignMessage()..c = 2])); + t..mergeFromProto3Json({ + 'repeatedForeignMessage': [ + {'c': 2}, + ], + 'optionalForeignMessage': {'c': 2}, + }), + TestAllTypes() + ..optionalForeignMessage = (ForeignMessage()..c = 2) + ..repeatedForeignMessage.addAll([ + ForeignMessage()..c = 1, + ForeignMessage()..c = 2, + ]), + ); expect(f, ForeignMessage()..c = 2); }); test('names_with_underscores', () { expect( - TestAllTypes() - ..mergeFromProto3Json({ - 'optional_foreign_message': {'c': 1} - }), - TestAllTypes()..optionalForeignMessage = (ForeignMessage()..c = 1)); + TestAllTypes()..mergeFromProto3Json({ + 'optional_foreign_message': {'c': 1}, + }), + TestAllTypes()..optionalForeignMessage = (ForeignMessage()..c = 1), + ); expect( - () => TestAllTypes() - ..mergeFromProto3Json({ - 'optional_foreign_message': {'c': 1} + () => + TestAllTypes()..mergeFromProto3Json({ + 'optional_foreign_message': {'c': 1}, }, supportNamesWithUnderscores: false), - parseFailure(['optional_foreign_message'])); + parseFailure(['optional_foreign_message']), + ); }); test('permissive enums', () { final sparseB = SparseEnumMessage()..sparseEnum = TestSparseEnum.SPARSE_B; expect( - SparseEnumMessage()..mergeFromProto3Json({'sparseEnum': 'SPARSE_B'}), - sparseB); - expect( - () => SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'sparse_b'}), - parseFailure(['sparseEnum'])); - expect( - () => SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'SPARSE-B'}), - parseFailure(['sparseEnum'])); - expect( - () => SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'sPaRsE_b'}), - parseFailure(['sparseEnum'])); - expect( - () => SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'sparseB'}), - parseFailure(['sparseEnum'])); - expect( - () => SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'spaRSEB'}), - parseFailure(['sparseEnum'])); - - expect(() => AMessage()..mergeFromProto3Json({'a': 'x'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'X'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'x_'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'X_'}), - parseFailure(['a'])); - expect( - AMessage()..mergeFromProto3Json({'a': '_x'}), AMessage()..a = A.x_); - expect(() => AMessage()..mergeFromProto3Json({'a': '_X'}), - parseFailure(['a'])); - - expect(() => AMessage()..mergeFromProto3Json({'a': 'y'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'Y'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'y_'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'Y_'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': '_y'}), - parseFailure(['a'])); + SparseEnumMessage()..mergeFromProto3Json({'sparseEnum': 'SPARSE_B'}), + sparseB, + ); + expect( + () => + SparseEnumMessage() + ..mergeFromProto3Json({'sparseEnum': 'sparse_b'}), + parseFailure(['sparseEnum']), + ); + expect( + () => + SparseEnumMessage() + ..mergeFromProto3Json({'sparseEnum': 'SPARSE-B'}), + parseFailure(['sparseEnum']), + ); + expect( + () => + SparseEnumMessage() + ..mergeFromProto3Json({'sparseEnum': 'sPaRsE_b'}), + parseFailure(['sparseEnum']), + ); expect( - AMessage()..mergeFromProto3Json({'a': '_Y'}), AMessage()..a = A.Y_); + () => + SparseEnumMessage()..mergeFromProto3Json({'sparseEnum': 'sparseB'}), + parseFailure(['sparseEnum']), + ); + expect( + () => + SparseEnumMessage()..mergeFromProto3Json({'sparseEnum': 'spaRSEB'}), + parseFailure(['sparseEnum']), + ); - expect(() => AMessage()..mergeFromProto3Json({'a': 'z'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'Z'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'z_'}), - parseFailure(['a'])); expect( - AMessage()..mergeFromProto3Json({'a': 'Z_'}), AMessage()..a = A.Z_); - expect(() => AMessage()..mergeFromProto3Json({'a': '_z'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': '_Z'}), - parseFailure(['a'])); + () => AMessage()..mergeFromProto3Json({'a': 'x'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'X'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'x_'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'X_'}), + parseFailure(['a']), + ); + expect( + AMessage()..mergeFromProto3Json({'a': '_x'}), + AMessage()..a = A.x_, + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': '_X'}), + parseFailure(['a']), + ); - expect(() => AMessage()..mergeFromProto3Json({'a': 'a_a'}), - parseFailure(['a'])); expect( - AMessage()..mergeFromProto3Json({'a': 'A_A'}), AMessage()..a = A.A_A); - expect(() => AMessage()..mergeFromProto3Json({'a': 'aA'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'AA'}), - parseFailure(['a'])); + () => AMessage()..mergeFromProto3Json({'a': 'y'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'Y'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'y_'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'Y_'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': '_y'}), + parseFailure(['a']), + ); + expect( + AMessage()..mergeFromProto3Json({'a': '_Y'}), + AMessage()..a = A.Y_, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'b_b'}), AMessage()..a = A.b_b); - expect(() => AMessage()..mergeFromProto3Json({'a': 'B_B'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'bB'}), - parseFailure(['a'])); - expect(() => AMessage()..mergeFromProto3Json({'a': 'BB'}), - parseFailure(['a'])); + () => AMessage()..mergeFromProto3Json({'a': 'z'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'Z'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'z_'}), + parseFailure(['a']), + ); + expect( + AMessage()..mergeFromProto3Json({'a': 'Z_'}), + AMessage()..a = A.Z_, + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': '_z'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': '_Z'}), + parseFailure(['a']), + ); + + expect( + () => AMessage()..mergeFromProto3Json({'a': 'a_a'}), + parseFailure(['a']), + ); + expect( + AMessage()..mergeFromProto3Json({'a': 'A_A'}), + AMessage()..a = A.A_A, + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'aA'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'AA'}), + parseFailure(['a']), + ); + + expect( + AMessage()..mergeFromProto3Json({'a': 'b_b'}), + AMessage()..a = A.b_b, + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'B_B'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'bB'}), + parseFailure(['a']), + ); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'BB'}), + parseFailure(['a']), + ); - expect(() => AMessage()..mergeFromProto3Json({'a': 'CAMEL_CASE'}), - parseFailure(['a'])); - expect(AMessage()..mergeFromProto3Json({'a': 'camelCase'}), - AMessage()..a = A.camelCase); + expect( + () => AMessage()..mergeFromProto3Json({'a': 'CAMEL_CASE'}), + parseFailure(['a']), + ); + expect( + AMessage()..mergeFromProto3Json({'a': 'camelCase'}), + AMessage()..a = A.camelCase, + ); - expect(AMessage()..mergeFromProto3Json({'a': 'x'}, permissiveEnums: true), - AMessage()..a = A.x_); - expect(AMessage()..mergeFromProto3Json({'a': 'X'}, permissiveEnums: true), - AMessage()..a = A.x_); expect( - AMessage()..mergeFromProto3Json({'a': 'x_'}, permissiveEnums: true), - AMessage()..a = A.x_); + AMessage()..mergeFromProto3Json({'a': 'x'}, permissiveEnums: true), + AMessage()..a = A.x_, + ); + expect( + AMessage()..mergeFromProto3Json({'a': 'X'}, permissiveEnums: true), + AMessage()..a = A.x_, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'X_'}, permissiveEnums: true), - AMessage()..a = A.x_); + AMessage()..mergeFromProto3Json({'a': 'x_'}, permissiveEnums: true), + AMessage()..a = A.x_, + ); expect( - AMessage()..mergeFromProto3Json({'a': '_x'}, permissiveEnums: true), - AMessage()..a = A.x_); + AMessage()..mergeFromProto3Json({'a': 'X_'}, permissiveEnums: true), + AMessage()..a = A.x_, + ); expect( - AMessage()..mergeFromProto3Json({'a': '_X'}, permissiveEnums: true), - AMessage()..a = A.x_); + AMessage()..mergeFromProto3Json({'a': '_x'}, permissiveEnums: true), + AMessage()..a = A.x_, + ); + expect( + AMessage()..mergeFromProto3Json({'a': '_X'}, permissiveEnums: true), + AMessage()..a = A.x_, + ); - expect(AMessage()..mergeFromProto3Json({'a': 'y'}, permissiveEnums: true), - AMessage()..a = A.Y_); - expect(AMessage()..mergeFromProto3Json({'a': 'Y'}, permissiveEnums: true), - AMessage()..a = A.Y_); expect( - AMessage()..mergeFromProto3Json({'a': 'y_'}, permissiveEnums: true), - AMessage()..a = A.Y_); + AMessage()..mergeFromProto3Json({'a': 'y'}, permissiveEnums: true), + AMessage()..a = A.Y_, + ); + expect( + AMessage()..mergeFromProto3Json({'a': 'Y'}, permissiveEnums: true), + AMessage()..a = A.Y_, + ); + expect( + AMessage()..mergeFromProto3Json({'a': 'y_'}, permissiveEnums: true), + AMessage()..a = A.Y_, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'Y_'}, permissiveEnums: true), - AMessage()..a = A.Y_); + AMessage()..mergeFromProto3Json({'a': 'Y_'}, permissiveEnums: true), + AMessage()..a = A.Y_, + ); expect( - AMessage()..mergeFromProto3Json({'a': '_y'}, permissiveEnums: true), - AMessage()..a = A.Y_); + AMessage()..mergeFromProto3Json({'a': '_y'}, permissiveEnums: true), + AMessage()..a = A.Y_, + ); expect( - AMessage()..mergeFromProto3Json({'a': '_Y'}, permissiveEnums: true), - AMessage()..a = A.Y_); + AMessage()..mergeFromProto3Json({'a': '_Y'}, permissiveEnums: true), + AMessage()..a = A.Y_, + ); - expect(AMessage()..mergeFromProto3Json({'a': 'z'}, permissiveEnums: true), - AMessage()..a = A.Z_); - expect(AMessage()..mergeFromProto3Json({'a': 'Z'}, permissiveEnums: true), - AMessage()..a = A.Z_); expect( - AMessage()..mergeFromProto3Json({'a': 'z_'}, permissiveEnums: true), - AMessage()..a = A.Z_); + AMessage()..mergeFromProto3Json({'a': 'z'}, permissiveEnums: true), + AMessage()..a = A.Z_, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'Z_'}, permissiveEnums: true), - AMessage()..a = A.Z_); + AMessage()..mergeFromProto3Json({'a': 'Z'}, permissiveEnums: true), + AMessage()..a = A.Z_, + ); expect( - AMessage()..mergeFromProto3Json({'a': '_z'}, permissiveEnums: true), - AMessage()..a = A.Z_); + AMessage()..mergeFromProto3Json({'a': 'z_'}, permissiveEnums: true), + AMessage()..a = A.Z_, + ); expect( - AMessage()..mergeFromProto3Json({'a': '_Z'}, permissiveEnums: true), - AMessage()..a = A.Z_); + AMessage()..mergeFromProto3Json({'a': 'Z_'}, permissiveEnums: true), + AMessage()..a = A.Z_, + ); + expect( + AMessage()..mergeFromProto3Json({'a': '_z'}, permissiveEnums: true), + AMessage()..a = A.Z_, + ); + expect( + AMessage()..mergeFromProto3Json({'a': '_Z'}, permissiveEnums: true), + AMessage()..a = A.Z_, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'a_a'}, permissiveEnums: true), - AMessage()..a = A.A_A); + AMessage()..mergeFromProto3Json({'a': 'a_a'}, permissiveEnums: true), + AMessage()..a = A.A_A, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'A_A'}, permissiveEnums: true), - AMessage()..a = A.A_A); + AMessage()..mergeFromProto3Json({'a': 'A_A'}, permissiveEnums: true), + AMessage()..a = A.A_A, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'aA'}, permissiveEnums: true), - AMessage()..a = A.A_A); + AMessage()..mergeFromProto3Json({'a': 'aA'}, permissiveEnums: true), + AMessage()..a = A.A_A, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'AA'}, permissiveEnums: true), - AMessage()..a = A.A_A); + AMessage()..mergeFromProto3Json({'a': 'AA'}, permissiveEnums: true), + AMessage()..a = A.A_A, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'b_b'}, permissiveEnums: true), - AMessage()..a = A.b_b); + AMessage()..mergeFromProto3Json({'a': 'b_b'}, permissiveEnums: true), + AMessage()..a = A.b_b, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'B_B'}, permissiveEnums: true), - AMessage()..a = A.b_b); + AMessage()..mergeFromProto3Json({'a': 'B_B'}, permissiveEnums: true), + AMessage()..a = A.b_b, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'bB'}, permissiveEnums: true), - AMessage()..a = A.b_b); + AMessage()..mergeFromProto3Json({'a': 'bB'}, permissiveEnums: true), + AMessage()..a = A.b_b, + ); expect( - AMessage()..mergeFromProto3Json({'a': 'BB'}, permissiveEnums: true), - AMessage()..a = A.b_b); + AMessage()..mergeFromProto3Json({'a': 'BB'}, permissiveEnums: true), + AMessage()..a = A.b_b, + ); expect( - AMessage() - ..mergeFromProto3Json({'a': 'CAMEL_CASE'}, permissiveEnums: true), - AMessage()..a = A.camelCase); + AMessage() + ..mergeFromProto3Json({'a': 'CAMEL_CASE'}, permissiveEnums: true), + AMessage()..a = A.camelCase, + ); expect( - AMessage() - ..mergeFromProto3Json({'a': 'camelCase'}, permissiveEnums: true), - AMessage()..a = A.camelCase); + AMessage() + ..mergeFromProto3Json({'a': 'camelCase'}, permissiveEnums: true), + AMessage()..a = A.camelCase, + ); expect( - SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'sparse_b'}, - permissiveEnums: true), - sparseB); + SparseEnumMessage()..mergeFromProto3Json({ + 'sparseEnum': 'sparse_b', + }, permissiveEnums: true), + sparseB, + ); expect( - SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'SPARSE-B'}, - permissiveEnums: true), - sparseB); + SparseEnumMessage()..mergeFromProto3Json({ + 'sparseEnum': 'SPARSE-B', + }, permissiveEnums: true), + sparseB, + ); expect( - SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'S-P-A-R-S-E-B'}, - permissiveEnums: true), - sparseB); + SparseEnumMessage()..mergeFromProto3Json({ + 'sparseEnum': 'S-P-A-R-S-E-B', + }, permissiveEnums: true), + sparseB, + ); expect( - SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'sPaRsE_b'}, - permissiveEnums: true), - sparseB); + SparseEnumMessage()..mergeFromProto3Json({ + 'sparseEnum': 'sPaRsE_b', + }, permissiveEnums: true), + sparseB, + ); expect( - SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'sparseB'}, - permissiveEnums: true), - sparseB); + SparseEnumMessage()..mergeFromProto3Json({ + 'sparseEnum': 'sparseB', + }, permissiveEnums: true), + sparseB, + ); expect( - SparseEnumMessage() - ..mergeFromProto3Json({'sparseEnum': 'spaRSEB'}, - permissiveEnums: true), - sparseB); + SparseEnumMessage()..mergeFromProto3Json({ + 'sparseEnum': 'spaRSEB', + }, permissiveEnums: true), + sparseB, + ); expect( - () => Any() - ..mergeFromProto3Json({ + () => + Any()..mergeFromProto3Json({ '@type': 'type.googleapis.com/protobuf_unittest.SparseEnumMessage', - 'sparseEnum': 'SPARSEB' + 'sparseEnum': 'SPARSEB', }, typeRegistry: TypeRegistry([SparseEnumMessage()])), - parseFailure(['sparseEnum'])); + parseFailure(['sparseEnum']), + ); expect( - Any() - ..mergeFromProto3Json({ - '@type': - 'type.googleapis.com/protobuf_unittest.SparseEnumMessage', - 'sparseEnum': 'SPARSEB' - }, - typeRegistry: TypeRegistry([SparseEnumMessage()]), - permissiveEnums: true), - Any.pack(sparseB), - reason: 'Parsing options are passed through Any messages'); + Any()..mergeFromProto3Json( + { + '@type': 'type.googleapis.com/protobuf_unittest.SparseEnumMessage', + 'sparseEnum': 'SPARSEB', + }, + typeRegistry: TypeRegistry([SparseEnumMessage()]), + permissiveEnums: true, + ), + Any.pack(sparseB), + reason: 'Parsing options are passed through Any messages', + ); }); test('map value', () { - final expected = TestMap() - ..int32ToInt32Field[32] = 32 - ..int32ToStringField[0] = 'foo' - ..int32ToStringField[1] = 'bar' - ..int32ToBytesField[-1] = [1, 2, 3] - ..int32ToEnumField[1] = TestMap_EnumValue.BAZ - ..int32ToMessageField[21] = (TestMap_MessageValue() - ..value = 2 - ..secondValue = 3) - ..stringToInt32Field['key'] = -1 - ..uint32ToInt32Field[0] = 0 - ..int64ToInt32Field[Int64.ZERO] = 0 - ..int64ToInt32Field[Int64.ONE] = 1 - ..int64ToInt32Field[-Int64.ONE] = -1 - ..int64ToInt32Field[Int64.MIN_VALUE] = -2 - ..int64ToInt32Field[Int64.MAX_VALUE] = 2 - ..uint64ToInt32Field[Int64.MIN_VALUE] = -2; - expect( + final expected = TestMap() - ..mergeFromProto3Json({ - 'int32ToInt32Field': {'32': 32}, - 'int32ToStringField': {'0': 'foo', '1': 'bar'}, - 'int32ToBytesField': {'-1': 'AQID'}, - 'int32ToEnumField': {'1': 'BAZ'}, - 'int32ToMessageField': { - '21': {'value': 2, 'secondValue': 3} - }, - 'stringToInt32Field': {'key': -1}, - 'uint32ToInt32Field': {'0': 0}, - 'int64ToInt32Field': { - '0': 0, - '1': 1, - '-1': -1, - '-9223372036854775808': -2, - '9223372036854775807': 2 - }, - 'uint64ToInt32Field': {'9223372036854775808': -2}, - }), - expected); + ..int32ToInt32Field[32] = 32 + ..int32ToStringField[0] = 'foo' + ..int32ToStringField[1] = 'bar' + ..int32ToBytesField[-1] = [1, 2, 3] + ..int32ToEnumField[1] = TestMap_EnumValue.BAZ + ..int32ToMessageField[21] = + (TestMap_MessageValue() + ..value = 2 + ..secondValue = 3) + ..stringToInt32Field['key'] = -1 + ..uint32ToInt32Field[0] = 0 + ..int64ToInt32Field[Int64.ZERO] = 0 + ..int64ToInt32Field[Int64.ONE] = 1 + ..int64ToInt32Field[-Int64.ONE] = -1 + ..int64ToInt32Field[Int64.MIN_VALUE] = -2 + ..int64ToInt32Field[Int64.MAX_VALUE] = 2 + ..uint64ToInt32Field[Int64.MIN_VALUE] = -2; + expect( + TestMap()..mergeFromProto3Json({ + 'int32ToInt32Field': {'32': 32}, + 'int32ToStringField': {'0': 'foo', '1': 'bar'}, + 'int32ToBytesField': {'-1': 'AQID'}, + 'int32ToEnumField': {'1': 'BAZ'}, + 'int32ToMessageField': { + '21': {'value': 2, 'secondValue': 3}, + }, + 'stringToInt32Field': {'key': -1}, + 'uint32ToInt32Field': {'0': 0}, + 'int64ToInt32Field': { + '0': 0, + '1': 1, + '-1': -1, + '-9223372036854775808': -2, + '9223372036854775807': 2, + }, + 'uint64ToInt32Field': {'9223372036854775808': -2}, + }), + expected, + ); expect(() => TestMap()..mergeFromProto3Json([]), parseFailure([])); expect( - () => TestMap() - ..mergeFromProto3Json({ - 'int32ToInt32Field': {'32': 'a'} + () => + TestMap()..mergeFromProto3Json({ + 'int32ToInt32Field': {'32': 'a'}, }), - parseFailure(['int32ToInt32Field', '32'])); + parseFailure(['int32ToInt32Field', '32']), + ); expect( - () => TestMap() - ..mergeFromProto3Json({ - 'int32ToInt32Field': {'2147483648': 1} + () => + TestMap()..mergeFromProto3Json({ + 'int32ToInt32Field': {'2147483648': 1}, }), - parseFailure(['int32ToInt32Field', '2147483648'])); + parseFailure(['int32ToInt32Field', '2147483648']), + ); expect( - () => TestMap() - ..mergeFromProto3Json({ - 'uint32ToInt32Field': {'-32': 21} + () => + TestMap()..mergeFromProto3Json({ + 'uint32ToInt32Field': {'-32': 21}, }), - parseFailure(['uint32ToInt32Field', '-32'])); + parseFailure(['uint32ToInt32Field', '-32']), + ); expect( - () => TestMap() - ..mergeFromProto3Json({ - 'uint32ToInt32Field': {'4294967296': 21} + () => + TestMap()..mergeFromProto3Json({ + 'uint32ToInt32Field': {'4294967296': 21}, }), - parseFailure(['uint32ToInt32Field', '4294967296'])); - expect( - TestMap() - ..mergeFromProto3Json({ - 'int32ToInt32Field': {'2': 21} - }), - TestMap()..int32ToInt32Field[2] = 21); + parseFailure(['uint32ToInt32Field', '4294967296']), + ); + expect( + TestMap()..mergeFromProto3Json({ + 'int32ToInt32Field': {'2': 21}, + }), + TestMap()..int32ToInt32Field[2] = 21, + ); }); test('ints', () { expect( - (TestAllTypes() - ..mergeFromProto3Json({ - 'optionalUint64': '17293822573397606400', - })) - .optionalUint64, - Int64.parseHex('f0000000ffff0000')); + (TestAllTypes() + ..mergeFromProto3Json({'optionalUint64': '17293822573397606400'})) + .optionalUint64, + Int64.parseHex('f0000000ffff0000'), + ); // TODO(sigurdm): This should throw. expect( - TestAllTypes() - ..mergeFromProto3Json({ - 'optionalUint64': '-1', - }), - TestAllTypes() - ..optionalUint64 = - Int64.fromBytes([255, 255, 255, 255, 255, 255, 255, 255])); + TestAllTypes()..mergeFromProto3Json({'optionalUint64': '-1'}), + TestAllTypes() + ..optionalUint64 = Int64.fromBytes([ + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + ]), + ); void expectRoundTrip(String typeName, int value) { - final t = TestAllTypes() - ..mergeFromProto3Json({ - typeName: value, - }); + final t = TestAllTypes()..mergeFromProto3Json({typeName: value}); expect(t.getField(t.getTagNumber(typeName)!), value); - final t2 = TestAllTypes() - ..mergeFromProto3Json({ - typeName: value.toString(), - }); + final t2 = + TestAllTypes()..mergeFromProto3Json({typeName: value.toString()}); expect(t2.getField(t2.getTagNumber(typeName)!), value); } void expectFailure(String typeName, int value) { expect( - () => TestAllTypes()..mergeFromProto3Json({typeName: -2147483649}), - parseFailure([typeName])); + () => TestAllTypes()..mergeFromProto3Json({typeName: -2147483649}), + parseFailure([typeName]), + ); } void expectSigned32(String typeName) { @@ -860,86 +1083,95 @@ void main() { test('unknown fields', () { expect( - () => TestAllTypes() - ..mergeFromProto3Json({ - 'myOwnInventedField': 'blahblahblah', - }), - throwsA(const TypeMatcher())); + () => + TestAllTypes() + ..mergeFromProto3Json({'myOwnInventedField': 'blahblahblah'}), + throwsA(const TypeMatcher()), + ); expect( - () => TestAllTypes() - ..mergeFromProto3Json({ + () => + TestAllTypes()..mergeFromProto3Json({ 'myOwnInventedField': 'blahblahblah', }, ignoreUnknownFields: false), - throwsA(const TypeMatcher())); - final t = TestAllTypes() - ..mergeFromProto3Json({ - 'myOwnInventedField': 'blahblahblah', - }, ignoreUnknownFields: true); + throwsA(const TypeMatcher()), + ); + final t = + TestAllTypes()..mergeFromProto3Json({ + 'myOwnInventedField': 'blahblahblah', + }, ignoreUnknownFields: true); expect(t, TestAllTypes()); expect(t.unknownFields.isEmpty, isTrue); }); test('Any', () { - final m1 = Any() - ..mergeFromProto3Json({ - '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', - 'optionalFixed64': '100' - }, typeRegistry: TypeRegistry([TestAllTypes()])); + final m1 = + Any()..mergeFromProto3Json({ + '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', + 'optionalFixed64': '100', + }, typeRegistry: TypeRegistry([TestAllTypes()])); expect(m1.unpackInto(TestAllTypes()).optionalFixed64, Int64(100)); - final m2 = Any() - ..mergeFromProto3Json({ - '@type': 'type.googleapis.com/google.protobuf.Timestamp', - 'value': '1969-07-20T19:17:00Z' - }, typeRegistry: TypeRegistry([Timestamp()])); + final m2 = + Any()..mergeFromProto3Json({ + '@type': 'type.googleapis.com/google.protobuf.Timestamp', + 'value': '1969-07-20T19:17:00Z', + }, typeRegistry: TypeRegistry([Timestamp()])); - expect(m2.unpackInto(Timestamp()).toDateTime().millisecondsSinceEpoch, - DateTime.utc(1969, 7, 20, 19, 17).millisecondsSinceEpoch); + expect( + m2.unpackInto(Timestamp()).toDateTime().millisecondsSinceEpoch, + DateTime.utc(1969, 7, 20, 19, 17).millisecondsSinceEpoch, + ); expect( - () => Any() - ..mergeFromProto3Json({ + () => + Any()..mergeFromProto3Json({ '@type': 'type.googleapis.com/google.protobuf.Timestamp', - 'value': '1969-07-20T19:17:00Z' + 'value': '1969-07-20T19:17:00Z', }), - parseFailure([])); + parseFailure([]), + ); expect( - () => Any() - ..mergeFromProto3Json( - {'@type': 11, 'value': '1969-07-20T19:17:00Z'}), - parseFailure([])); + () => + Any()..mergeFromProto3Json({ + '@type': 11, + 'value': '1969-07-20T19:17:00Z', + }), + parseFailure([]), + ); - final m3 = Any() - ..mergeFromProto3Json({ - '@type': 'type.googleapis.com/google.protobuf.Any', - 'value': { - '@type': 'type.googleapis.com/google.protobuf.Timestamp', - 'value': '1969-07-20T19:17:00Z' - } - }, typeRegistry: TypeRegistry([Timestamp(), Any()])); + final m3 = + Any()..mergeFromProto3Json({ + '@type': 'type.googleapis.com/google.protobuf.Any', + 'value': { + '@type': 'type.googleapis.com/google.protobuf.Timestamp', + 'value': '1969-07-20T19:17:00Z', + }, + }, typeRegistry: TypeRegistry([Timestamp(), Any()])); expect( - m3 - .unpackInto(Any()) - .unpackInto(Timestamp()) - .toDateTime() - .millisecondsSinceEpoch, - DateTime.utc(1969, 7, 20, 19, 17).millisecondsSinceEpoch); + m3 + .unpackInto(Any()) + .unpackInto(Timestamp()) + .toDateTime() + .millisecondsSinceEpoch, + DateTime.utc(1969, 7, 20, 19, 17).millisecondsSinceEpoch, + ); // TODO(sigurdm): We would ideally like the error path to be // ['value', 'value']. expect( - () => Any() - ..mergeFromProto3Json({ + () => + Any()..mergeFromProto3Json({ '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/google.protobuf.Timestamp', - 'value': '1969' - } + 'value': '1969', + }, }, typeRegistry: TypeRegistry([Timestamp(), Any()])), - parseFailure([])); + parseFailure([]), + ); expect(() => Any()..mergeFromProto3Json('@type'), parseFailure([])); @@ -948,242 +1180,276 @@ void main() { expect(() => Any()..mergeFromProto3Json(['@type']), parseFailure([])); expect( - () => Any() - ..mergeFromProto3Json({ + () => + Any()..mergeFromProto3Json({ '@type': 'type.googleapis.com/google.protobuf.Timestamp', - 'value': '1969-07-20T19:17:00Z' + 'value': '1969-07-20T19:17:00Z', }), - parseFailure([])); + parseFailure([]), + ); }); test('Nested Any', () { - final m1 = Any() - ..mergeFromProto3Json({ - 'anyField2': { - 'value': '1', - '@type': 'type.googleapis.com/nested_any.AnyMessage1' - }, - 'value': '2', - '@type': 'type.googleapis.com/nested_any.AnyMessage2' - }, typeRegistry: TypeRegistry([AnyMessage1(), AnyMessage2()])); + final m1 = + Any()..mergeFromProto3Json({ + 'anyField2': { + 'value': '1', + '@type': 'type.googleapis.com/nested_any.AnyMessage1', + }, + 'value': '2', + '@type': 'type.googleapis.com/nested_any.AnyMessage2', + }, typeRegistry: TypeRegistry([AnyMessage1(), AnyMessage2()])); expect( - m1 - .unpackInto(AnyMessage2()) - .anyField2 - .unpackInto(AnyMessage1()) - .value, - '1'); + m1.unpackInto(AnyMessage2()).anyField2.unpackInto(AnyMessage1()).value, + '1', + ); }); test('Duration', () { expect( - Duration()..mergeFromProto3Json('0s'), - Duration() - ..seconds = Int64(0) - ..nanos = 0); - expect( - Duration()..mergeFromProto3Json('10s'), - Duration() - ..seconds = Int64(10) - ..nanos = 0); - expect( - Duration()..mergeFromProto3Json('10.000000001s'), - Duration() - ..seconds = Int64(10) - ..nanos = 1); - expect( - Duration()..mergeFromProto3Json('10.00000001s'), - Duration() - ..seconds = Int64(10) - ..nanos = 10); - expect( - Duration()..mergeFromProto3Json('-1.000099s'), - Duration() - ..seconds = -Int64(1) - ..nanos = -99000); - - expect( - Duration()..mergeFromProto3Json('0.s'), - Duration() - ..seconds = Int64(0) - ..nanos = 0); - expect( - Duration()..mergeFromProto3Json('.0s'), - Duration() - ..seconds = Int64(0) - ..nanos = 0); - expect( - Duration()..mergeFromProto3Json('.5s'), - Duration() - ..seconds = Int64(0) - ..nanos = 500000000); - expect( - Duration()..mergeFromProto3Json('5.s'), - Duration() - ..seconds = Int64(5) - ..nanos = 0); - expect( - Duration()..mergeFromProto3Json('.s'), - Duration() - ..seconds = Int64(0) - ..nanos = 0); + Duration()..mergeFromProto3Json('0s'), + Duration() + ..seconds = Int64(0) + ..nanos = 0, + ); + expect( + Duration()..mergeFromProto3Json('10s'), + Duration() + ..seconds = Int64(10) + ..nanos = 0, + ); + expect( + Duration()..mergeFromProto3Json('10.000000001s'), + Duration() + ..seconds = Int64(10) + ..nanos = 1, + ); + expect( + Duration()..mergeFromProto3Json('10.00000001s'), + Duration() + ..seconds = Int64(10) + ..nanos = 10, + ); + expect( + Duration()..mergeFromProto3Json('-1.000099s'), + Duration() + ..seconds = -Int64(1) + ..nanos = -99000, + ); + + expect( + Duration()..mergeFromProto3Json('0.s'), + Duration() + ..seconds = Int64(0) + ..nanos = 0, + ); + expect( + Duration()..mergeFromProto3Json('.0s'), + Duration() + ..seconds = Int64(0) + ..nanos = 0, + ); + expect( + Duration()..mergeFromProto3Json('.5s'), + Duration() + ..seconds = Int64(0) + ..nanos = 500000000, + ); + expect( + Duration()..mergeFromProto3Json('5.s'), + Duration() + ..seconds = Int64(5) + ..nanos = 0, + ); + expect( + Duration()..mergeFromProto3Json('.s'), + Duration() + ..seconds = Int64(0) + ..nanos = 0, + ); expect(() => Duration()..mergeFromProto3Json('0.5'), parseFailure([])); expect(() => Duration()..mergeFromProto3Json(100), parseFailure([])); }); test('Timestamp', () { - expect(Timestamp()..mergeFromProto3Json('1969-07-20T20:17:00Z'), - Timestamp.fromDateTime(DateTime.utc(1969, 7, 20, 20, 17))); - expect( - Timestamp()..mergeFromProto3Json('1970-01-01T00:00:00.000000001Z'), - Timestamp() - ..seconds = Int64(0) - ..nanos = 1); - expect(Timestamp()..mergeFromProto3Json('1970-01-01T00:00:00.008200Z'), - Timestamp.fromDateTime(DateTime.utc(1970))..nanos = 8200000); - expect( - Timestamp()..mergeFromProto3Json('1970-01-01T18:50:00-04:00'), - Timestamp() - ..seconds = Int64(82200) - ..nanos = 0); - expect( - Timestamp()..mergeFromProto3Json('1970-01-01T18:50:00+04:00'), - Timestamp() - ..seconds = Int64(53400) - ..nanos = 0); - expect( - Timestamp()..mergeFromProto3Json('1970-01-01T18:50:00.0001+04:00'), - Timestamp() - ..seconds = Int64(53400) - ..nanos = 100000); - expect( - () => Timestamp() - ..mergeFromProto3Json('1970-01-01T00:00:00.0000000001Z'), - parseFailure([])); + expect( + Timestamp()..mergeFromProto3Json('1969-07-20T20:17:00Z'), + Timestamp.fromDateTime(DateTime.utc(1969, 7, 20, 20, 17)), + ); + expect( + Timestamp()..mergeFromProto3Json('1970-01-01T00:00:00.000000001Z'), + Timestamp() + ..seconds = Int64(0) + ..nanos = 1, + ); + expect( + Timestamp()..mergeFromProto3Json('1970-01-01T00:00:00.008200Z'), + Timestamp.fromDateTime(DateTime.utc(1970))..nanos = 8200000, + ); + expect( + Timestamp()..mergeFromProto3Json('1970-01-01T18:50:00-04:00'), + Timestamp() + ..seconds = Int64(82200) + ..nanos = 0, + ); + expect( + Timestamp()..mergeFromProto3Json('1970-01-01T18:50:00+04:00'), + Timestamp() + ..seconds = Int64(53400) + ..nanos = 0, + ); + expect( + Timestamp()..mergeFromProto3Json('1970-01-01T18:50:00.0001+04:00'), + Timestamp() + ..seconds = Int64(53400) + ..nanos = 100000, + ); + expect( + () => + Timestamp()..mergeFromProto3Json('1970-01-01T00:00:00.0000000001Z'), + parseFailure([]), + ); expect(() => Timestamp()..mergeFromProto3Json(1970), parseFailure([])); - expect(() => Timestamp()..mergeFromProto3Json('1970-01-01T18:50:00.'), - parseFailure([])); + expect( + () => Timestamp()..mergeFromProto3Json('1970-01-01T18:50:00.'), + parseFailure([]), + ); }); test('wrapper types', () { expect( - TestWellKnownTypes() - ..mergeFromProto3Json({ - 'doubleField': 10.01, - 'floatField': 3, - 'int64Field': '-9223372036854775808', - 'uint64Field': '9223372036854775808', - 'int32Field': 101, - 'uint32Field': 102, - 'boolField': false, - 'stringField': 'Pop', - 'bytesField': 'CAkK', - }), - TestWellKnownTypes() - ..doubleField = (DoubleValue()..value = 10.01) - ..floatField = (FloatValue()..value = 3.0) - ..int64Field = (Int64Value()..value = Int64.MIN_VALUE) - ..uint64Field = (UInt64Value()..value = Int64.MIN_VALUE) - ..int32Field = (Int32Value()..value = 101) - ..uint32Field = (UInt32Value()..value = 102) - ..boolField = (BoolValue()..value = false) - ..stringField = (StringValue()..value = 'Pop') - ..bytesField = (BytesValue()..value = [8, 9, 10])); - - expect( - TestWellKnownTypes() - ..mergeFromProto3Json({ - 'doubleField': '10.01', - 'floatField': '3', - 'int64Field': -854775808, - 'uint64Field': 854775808, - 'int32Field': '101', - 'uint32Field': '102', - 'boolField': false, - }), - TestWellKnownTypes() - ..doubleField = (DoubleValue()..value = 10.01) - ..floatField = (FloatValue()..value = 3.0) - ..int64Field = (Int64Value()..value = Int64(-854775808)) - ..uint64Field = (UInt64Value()..value = Int64(854775808)) - ..int32Field = (Int32Value()..value = 101) - ..uint32Field = (UInt32Value()..value = 102) - ..boolField = (BoolValue()..value = false), - reason: 'alternative representations should be accepted'); - - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'doubleField': 'a'}), - parseFailure(['doubleField'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'doubleField': {}}), - parseFailure(['doubleField'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'floatField': 'a'}), - parseFailure(['floatField'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'floatField': {}}), - parseFailure(['floatField'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'int64Field': 'a'}), - parseFailure(['int64Field'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'int64Field': {}}), - parseFailure(['int64Field'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'int64Field': 10.4}), - parseFailure(['int64Field'])); - - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'uint64Field': 'a'}), - parseFailure(['uint64Field'])); - expect( - () => - TestWellKnownTypes()..mergeFromProto3Json({'uint64Field': 10.4}), - parseFailure(['uint64Field'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'int32Field': 'a'}), - parseFailure(['int32Field'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'int32Field': 10.4}), - parseFailure(['int32Field'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'uint32Field': 'a'}), - parseFailure(['uint32Field'])); - expect( - () => - TestWellKnownTypes()..mergeFromProto3Json({'uint32Field': 10.4}), - parseFailure(['uint32Field'])); - expect( - () => - TestWellKnownTypes()..mergeFromProto3Json({'boolField': 'false'}), - parseFailure(['boolField'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'stringField': 22}), - parseFailure(['stringField'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'bytesField': 22}), - parseFailure(['bytesField'])); - expect( - () => TestWellKnownTypes()..mergeFromProto3Json({'bytesField': '()'}), - parseFailure(['bytesField'])); - - expect( - TestWellKnownTypes() - ..mergeFromProto3Json({ - 'doubleField': null, - 'floatField': null, - 'int64Field': null, - 'uint64Field': null, - 'int32Field': null, - 'uint32Field': null, - 'boolField': null, - 'stringField': null, - 'bytesField': null, - }), - TestWellKnownTypes(), - reason: 'having fields of wrapper types set to null will return an ' - 'empty wrapper (with unset .value field)'); + TestWellKnownTypes()..mergeFromProto3Json({ + 'doubleField': 10.01, + 'floatField': 3, + 'int64Field': '-9223372036854775808', + 'uint64Field': '9223372036854775808', + 'int32Field': 101, + 'uint32Field': 102, + 'boolField': false, + 'stringField': 'Pop', + 'bytesField': 'CAkK', + }), + TestWellKnownTypes() + ..doubleField = (DoubleValue()..value = 10.01) + ..floatField = (FloatValue()..value = 3.0) + ..int64Field = (Int64Value()..value = Int64.MIN_VALUE) + ..uint64Field = (UInt64Value()..value = Int64.MIN_VALUE) + ..int32Field = (Int32Value()..value = 101) + ..uint32Field = (UInt32Value()..value = 102) + ..boolField = (BoolValue()..value = false) + ..stringField = (StringValue()..value = 'Pop') + ..bytesField = (BytesValue()..value = [8, 9, 10]), + ); + + expect( + TestWellKnownTypes()..mergeFromProto3Json({ + 'doubleField': '10.01', + 'floatField': '3', + 'int64Field': -854775808, + 'uint64Field': 854775808, + 'int32Field': '101', + 'uint32Field': '102', + 'boolField': false, + }), + TestWellKnownTypes() + ..doubleField = (DoubleValue()..value = 10.01) + ..floatField = (FloatValue()..value = 3.0) + ..int64Field = (Int64Value()..value = Int64(-854775808)) + ..uint64Field = (UInt64Value()..value = Int64(854775808)) + ..int32Field = (Int32Value()..value = 101) + ..uint32Field = (UInt32Value()..value = 102) + ..boolField = (BoolValue()..value = false), + reason: 'alternative representations should be accepted', + ); + + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'doubleField': 'a'}), + parseFailure(['doubleField']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'doubleField': {}}), + parseFailure(['doubleField']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'floatField': 'a'}), + parseFailure(['floatField']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'floatField': {}}), + parseFailure(['floatField']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'int64Field': 'a'}), + parseFailure(['int64Field']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'int64Field': {}}), + parseFailure(['int64Field']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'int64Field': 10.4}), + parseFailure(['int64Field']), + ); + + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'uint64Field': 'a'}), + parseFailure(['uint64Field']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'uint64Field': 10.4}), + parseFailure(['uint64Field']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'int32Field': 'a'}), + parseFailure(['int32Field']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'int32Field': 10.4}), + parseFailure(['int32Field']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'uint32Field': 'a'}), + parseFailure(['uint32Field']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'uint32Field': 10.4}), + parseFailure(['uint32Field']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'boolField': 'false'}), + parseFailure(['boolField']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'stringField': 22}), + parseFailure(['stringField']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'bytesField': 22}), + parseFailure(['bytesField']), + ); + expect( + () => TestWellKnownTypes()..mergeFromProto3Json({'bytesField': '()'}), + parseFailure(['bytesField']), + ); + + expect( + TestWellKnownTypes()..mergeFromProto3Json({ + 'doubleField': null, + 'floatField': null, + 'int64Field': null, + 'uint64Field': null, + 'int32Field': null, + 'uint32Field': null, + 'boolField': null, + 'stringField': null, + 'bytesField': null, + }), + TestWellKnownTypes(), + reason: + 'having fields of wrapper types set to null will return an ' + 'empty wrapper (with unset .value field)', + ); }); test('struct', () { @@ -1193,54 +1459,78 @@ void main() { 'string': 'foo', 'bool': false, 'struct': {'a': 0}, - 'list': [{}, [], 'why'] + 'list': [{}, [], 'why'], }; - final s = Struct() - ..fields['null'] = (Value()..nullValue = NullValue.NULL_VALUE) - ..fields['number'] = (Value()..numberValue = 22.3) - ..fields['string'] = (Value()..stringValue = 'foo') - ..fields['bool'] = (Value()..boolValue = false) - ..fields['struct'] = (Value() - ..structValue = - (Struct()..fields['a'] = (Value()..numberValue = 0.0))) - ..fields['list'] = (Value() - ..listValue = (ListValue() - ..values.addAll([ - Value()..structValue = Struct(), - Value()..listValue = ListValue(), - Value()..stringValue = 'why' - ]))); + final s = + Struct() + ..fields['null'] = (Value()..nullValue = NullValue.NULL_VALUE) + ..fields['number'] = (Value()..numberValue = 22.3) + ..fields['string'] = (Value()..stringValue = 'foo') + ..fields['bool'] = (Value()..boolValue = false) + ..fields['struct'] = + (Value() + ..structValue = + (Struct()..fields['a'] = (Value()..numberValue = 0.0))) + ..fields['list'] = + (Value() + ..listValue = + (ListValue() + ..values.addAll([ + Value()..structValue = Struct(), + Value()..listValue = ListValue(), + Value()..stringValue = 'why', + ]))); expect(Struct()..mergeFromProto3Json(f), s); - expect(Struct()..mergeFromProto3Json({'a': 12}), - (Struct()..fields['a'] = (Value()..numberValue = 12.0)), - reason: 'Allow key type to be `dynamic`'); + expect( + Struct()..mergeFromProto3Json({'a': 12}), + (Struct()..fields['a'] = (Value()..numberValue = 12.0)), + reason: 'Allow key type to be `dynamic`', + ); - expect(() => Struct()..mergeFromProto3Json({1: 2}), parseFailure([]), - reason: 'Non-string key in JSON object literal'); + expect( + () => Struct()..mergeFromProto3Json({1: 2}), + parseFailure([]), + reason: 'Non-string key in JSON object literal', + ); - expect(() => Struct()..mergeFromProto3Json([]), parseFailure([]), - reason: 'Non object literal'); + expect( + () => Struct()..mergeFromProto3Json([]), + parseFailure([]), + reason: 'Non object literal', + ); - expect(() => Struct()..mergeFromProto3Json([]), parseFailure([]), - reason: 'Non-string key in JSON object literal'); + expect( + () => Struct()..mergeFromProto3Json([]), + parseFailure([]), + reason: 'Non-string key in JSON object literal', + ); - expect(() => Value()..mergeFromProto3Json(Object()), parseFailure([]), - reason: 'Non JSON value'); + expect( + () => Value()..mergeFromProto3Json(Object()), + parseFailure([]), + reason: 'Non JSON value', + ); - expect(() => ListValue()..mergeFromProto3Json({}), parseFailure([]), - reason: 'Non-list'); + expect( + () => ListValue()..mergeFromProto3Json({}), + parseFailure([]), + reason: 'Non-list', + ); }); test('field mask', () { expect( - TestWellKnownTypes() - ..mergeFromProto3Json({'fieldMaskField': 'foo,barBaz'}), - TestWellKnownTypes() - ..fieldMaskField = (FieldMask()..paths.addAll(['foo', 'bar_baz']))); - expect(() => FieldMask()..mergeFromProto3Json('foo,bar_bar'), - parseFailure([])); + TestWellKnownTypes() + ..mergeFromProto3Json({'fieldMaskField': 'foo,barBaz'}), + TestWellKnownTypes() + ..fieldMaskField = (FieldMask()..paths.addAll(['foo', 'bar_baz'])), + ); + expect( + () => FieldMask()..mergeFromProto3Json('foo,bar_bar'), + parseFailure([]), + ); expect(FieldMask()..mergeFromProto3Json(''), FieldMask()); expect(() => FieldMask()..mergeFromProto3Json(12), parseFailure([])); diff --git a/protoc_plugin/test/repeated_encoding_test.dart b/protoc_plugin/test/repeated_encoding_test.dart index ac3e1370e..36463d452 100644 --- a/protoc_plugin/test/repeated_encoding_test.dart +++ b/protoc_plugin/test/repeated_encoding_test.dart @@ -15,20 +15,21 @@ void main() { proto2.intsNotPacked.addAll([1, 2]); final proto2Encoded = proto2.writeToBuffer(); expect( - proto2Encoded.toList(), - equals([ - 8, // field = 1, type = varint - 1, // value = 1 - 8, // field = 1, type = varint - 2, // value = 2 - 18, // field = 2, type = length delimited - 2, // length = 2 - 1, 2, // values = [1, 2] - 24, // field = 3, type = varint - 1, // value = 1 - 24, // field = 3, type = varint - 2, // value = 2 - ])); + proto2Encoded.toList(), + equals([ + 8, // field = 1, type = varint + 1, // value = 1 + 8, // field = 1, type = varint + 2, // value = 2 + 18, // field = 2, type = length delimited + 2, // length = 2 + 1, 2, // values = [1, 2] + 24, // field = 3, type = varint + 1, // value = 1 + 24, // field = 3, type = varint + 2, // value = 2 + ]), + ); final proto3 = Proto3Repeated(); proto3.intsDefault.addAll([1, 2]); @@ -36,18 +37,19 @@ void main() { proto3.intsNotPacked.addAll([1, 2]); final proto3Encoded = proto3.writeToBuffer(); expect( - proto3Encoded.toList(), - equals([ - 10, // field = 1, type = length delimited - 2, // length = 2 - 1, 2, // values = [1, 2] - 18, // field = 2, type = length delimited - 2, // length = 2 - 1, 2, // values = [1, 2] - 24, // field = 3, type = varint - 1, // value = 1 - 24, // field = 3, type = varint - 2, // value = 2 - ])); + proto3Encoded.toList(), + equals([ + 10, // field = 1, type = length delimited + 2, // length = 2 + 1, 2, // values = [1, 2] + 18, // field = 2, type = length delimited + 2, // length = 2 + 1, 2, // values = [1, 2] + 24, // field = 3, type = varint + 1, // value = 1 + 24, // field = 3, type = varint + 2, // value = 2 + ]), + ); }); } diff --git a/protoc_plugin/test/repeated_field_test.dart b/protoc_plugin/test/repeated_field_test.dart index 237b32c6e..1c30e722b 100644 --- a/protoc_plugin/test/repeated_field_test.dart +++ b/protoc_plugin/test/repeated_field_test.dart @@ -11,33 +11,30 @@ void main() { test('check properties are initialized for repeated fields', () { final msg = TestAllTypes(); expect( - (msg.info_.byName['repeatedNestedMessage'] - as FieldInfo) - .check, - isNotNull); + (msg.info_.byName['repeatedNestedMessage'] + as FieldInfo) + .check, + isNotNull, + ); expect( - (msg.info_.byName['repeatedgroup'] - as FieldInfo) - .check, - isNotNull); + (msg.info_.byName['repeatedgroup'] + as FieldInfo) + .check, + isNotNull, + ); expect( - (msg.info_.byName['repeatedNestedEnum'] - as FieldInfo) - .check, - isNotNull); + (msg.info_.byName['repeatedNestedEnum'] + as FieldInfo) + .check, + isNotNull, + ); }); test('check read-only default list type', () { final msg = TestAllTypes()..freeze(); final list = msg.repeatedInt32; - expect( - list.firstWhere( - (msgParam) => false, - orElse: () => 123, - ), - 123, - ); + expect(list.firstWhere((msgParam) => false, orElse: () => 123), 123); }); } diff --git a/protoc_plugin/test/reserved_names_test.dart b/protoc_plugin/test/reserved_names_test.dart index 6a56072f8..2158b9ab2 100644 --- a/protoc_plugin/test/reserved_names_test.dart +++ b/protoc_plugin/test/reserved_names_test.dart @@ -19,23 +19,29 @@ import 'src/mirror_util.dart' show findMemberNames; void main() { test('GeneratedMessage reserved names are up to date', () { final actual = Set.from(GeneratedMessage_reservedNames); - final expected = - findMemberNames('package:protobuf/protobuf.dart', #GeneratedMessage); + final expected = findMemberNames( + 'package:protobuf/protobuf.dart', + #GeneratedMessage, + ); expect(actual.toList()..sort(), equals(expected.toList()..sort())); }); test('ProtobufEnum reserved names are up to date', () { final actual = Set.from(ProtobufEnum_reservedNames); - final expected = - findMemberNames('package:protobuf/protobuf.dart', #ProtobufEnum); + final expected = findMemberNames( + 'package:protobuf/protobuf.dart', + #ProtobufEnum, + ); expect(actual.toList()..sort(), equals(expected.toList()..sort())); }); test("ReadonlyMessageMixin doesn't add any reserved names", () { final mixinNames = findMemberNames( - 'package:protobuf/protobuf.dart', #ReadonlyMessageMixin); + 'package:protobuf/protobuf.dart', + #ReadonlyMessageMixin, + ); final reservedNames = Set.from(GeneratedMessage_reservedNames); for (final name in mixinNames) { if (name == 'ReadonlyMessageMixin' || name == 'unknownFields') continue; @@ -49,11 +55,14 @@ void main() { final meta = findMixin('PbMapMixin')!; final actual = Set.from(meta.findReservedNames()); - final expected = findMemberNames(meta.importFrom, #PbMapMixin) - ..addAll(findMemberNames('dart:collection', #MapMixin)) - ..removeAll(GeneratedMessage_reservedNames); + final expected = + findMemberNames(meta.importFrom, #PbMapMixin) + ..addAll(findMemberNames('dart:collection', #MapMixin)) + ..removeAll(GeneratedMessage_reservedNames); expect( - actual.toList()..sort(), containsAllInOrder(expected.toList()..sort())); + actual.toList()..sort(), + containsAllInOrder(expected.toList()..sort()), + ); }); } diff --git a/protoc_plugin/test/send_protos_via_sendports_test.dart b/protoc_plugin/test/send_protos_via_sendports_test.dart index 936c8f93a..39b8b8a20 100644 --- a/protoc_plugin/test/send_protos_via_sendports_test.dart +++ b/protoc_plugin/test/send_protos_via_sendports_test.dart @@ -16,43 +16,54 @@ Future sendReceive(T object) async { } void main() async { - test('Normal proto can be transferred via ports', () async { - final object = Outer() - ..inner = (Inner()..value = 'pip') - ..inners.add(Inner()..value = 'pop'); - - final clone = await sendReceive(object); - - // Ensure the clone is actually containing the same data. - expect(clone, equals(object)); - expect(clone.toString(), equals(object.toString())); - expect(clone.toDebugString(), equals(object.toDebugString())); - expect(clone.writeToBuffer(), equals(object.writeToBuffer())); - - // Ensure the actual objects got transitively cloned, but the metadata in - // the `_info_` did not get cloned. - expect(!identical(object, clone), true); - expect(!identical(object.inner, clone.inner), true); - expect(identical(object.info_, clone.info_), true); - }, onPlatform: {'js': Skip('dart:isolate only works on Dart VM')}); - - test('Map-using proto can be transferred via ports', () async { - final object = map.TestMap() - ..int32ToMessageField[42] = (map.TestMap_MessageValue() - ..value = 1 - ..secondValue = 2); - - final clone = await sendReceive(object); - - // Ensure the clone is actually containing the same data. - expect(clone, equals(object)); - expect(clone.toString(), equals(object.toString())); - expect(clone.toDebugString(), equals(object.toDebugString())); - expect(clone.writeToBuffer(), equals(object.writeToBuffer())); - - // Ensure the actual objects got transitively cloned, but the metadata in - // the `_info_` did not get cloned. - expect(!identical(object, clone), true); - expect(identical(object.info_, clone.info_), true); - }, onPlatform: {'js': Skip('dart:isolate only works on Dart VM')}); + test( + 'Normal proto can be transferred via ports', + () async { + final object = + Outer() + ..inner = (Inner()..value = 'pip') + ..inners.add(Inner()..value = 'pop'); + + final clone = await sendReceive(object); + + // Ensure the clone is actually containing the same data. + expect(clone, equals(object)); + expect(clone.toString(), equals(object.toString())); + expect(clone.toDebugString(), equals(object.toDebugString())); + expect(clone.writeToBuffer(), equals(object.writeToBuffer())); + + // Ensure the actual objects got transitively cloned, but the metadata in + // the `_info_` did not get cloned. + expect(!identical(object, clone), true); + expect(!identical(object.inner, clone.inner), true); + expect(identical(object.info_, clone.info_), true); + }, + onPlatform: {'js': Skip('dart:isolate only works on Dart VM')}, + ); + + test( + 'Map-using proto can be transferred via ports', + () async { + final object = + map.TestMap() + ..int32ToMessageField[42] = + (map.TestMap_MessageValue() + ..value = 1 + ..secondValue = 2); + + final clone = await sendReceive(object); + + // Ensure the clone is actually containing the same data. + expect(clone, equals(object)); + expect(clone.toString(), equals(object.toString())); + expect(clone.toDebugString(), equals(object.toDebugString())); + expect(clone.writeToBuffer(), equals(object.writeToBuffer())); + + // Ensure the actual objects got transitively cloned, but the metadata in + // the `_info_` did not get cloned. + expect(!identical(object, clone), true); + expect(identical(object.info_, clone.info_), true); + }, + onPlatform: {'js': Skip('dart:isolate only works on Dart VM')}, + ); } diff --git a/protoc_plugin/test/service_generator_test.dart b/protoc_plugin/test/service_generator_test.dart index 706ccfa73..e501b6687 100644 --- a/protoc_plugin/test/service_generator_test.dart +++ b/protoc_plugin/test/service_generator_test.dart @@ -14,13 +14,17 @@ import 'src/service_util.dart'; void main() { test('testServiceGenerator', () { final options = GenerationOptions(); - final fd = buildFileDescriptor( - 'testpkg', 'testpkg.proto', ['SomeRequest', 'SomeReply']); + final fd = buildFileDescriptor('testpkg', 'testpkg.proto', [ + 'SomeRequest', + 'SomeReply', + ]); fd.service.add(buildServiceDescriptor()); final fg = FileGenerator(fd, options); - final fd2 = buildFileDescriptor( - 'foo.bar', 'foobar.proto', ['EmptyMessage', 'AnotherReply']); + final fd2 = buildFileDescriptor('foo.bar', 'foobar.proto', [ + 'EmptyMessage', + 'AnotherReply', + ]); final fg2 = FileGenerator(fd2, options); link(GenerationOptions(), [fg, fg2]); diff --git a/protoc_plugin/test/service_test.dart b/protoc_plugin/test/service_test.dart index 9503b76b5..f260ab8da 100644 --- a/protoc_plugin/test/service_test.dart +++ b/protoc_plugin/test/service_test.dart @@ -14,7 +14,9 @@ import 'gen/service3.pb.dart' as pb3; class SearchService extends pb.SearchServiceBase { @override Future search( - ServerContext ctx, pb.SearchRequest request) async { + ServerContext ctx, + pb.SearchRequest request, + ) async { final out = pb.SearchResponse(); if (request.query == 'hello' || request.query == 'world') { out.result.add('hello, world!'); @@ -24,12 +26,15 @@ class SearchService extends pb.SearchServiceBase { @override Future search2( - ServerContext ctx, pb2.SearchRequest request) async { + ServerContext ctx, + pb2.SearchRequest request, + ) async { final out = pb2.SearchResponse(); if (request.query == '2') { - final result = pb3.SearchResult() - ..url = 'http://example.com/' - ..snippet = 'hello world (2)!'; + final result = + pb3.SearchResult() + ..url = 'http://example.com/' + ..snippet = 'hello world (2)!'; out.results.add(result); } return out; @@ -41,7 +46,10 @@ class FakeJsonServer { FakeJsonServer(this.searchService); Future messageHandler( - String serviceName, String methodName, String requestJson) async { + String serviceName, + String methodName, + String requestJson, + ) async { if (serviceName == 'SearchService') { final request = searchService.createRequest(methodName); request.mergeFromJson(requestJson); @@ -61,14 +69,18 @@ class FakeJsonClient implements RpcClient { @override Future invoke( - ClientContext? ctx, - String serviceName, - String methodName, - GeneratedMessage request, - T response) async { + ClientContext? ctx, + String serviceName, + String methodName, + GeneratedMessage request, + T response, + ) async { final requestJson = request.writeToJson(); - final replyJson = - await server.messageHandler(serviceName, methodName, requestJson); + final replyJson = await server.messageHandler( + serviceName, + methodName, + requestJson, + ); response.mergeFromJson(replyJson); return response; } @@ -94,8 +106,8 @@ void main() { }); test('can read service descriptor from JSON', () { - final descriptor = ServiceDescriptorProto() - ..mergeFromJsonMap(service.$json); + final descriptor = + ServiceDescriptorProto()..mergeFromJsonMap(service.$json); expect(descriptor.name, 'SearchService'); final methodNames = descriptor.method.map((m) => m.name).toList(); expect(methodNames, ['Search', 'Search2']); diff --git a/protoc_plugin/test/src/golden_file.dart b/protoc_plugin/test/src/golden_file.dart index 6b8d2b066..fbc158c82 100644 --- a/protoc_plugin/test/src/golden_file.dart +++ b/protoc_plugin/test/src/golden_file.dart @@ -44,6 +44,6 @@ void expectGolden(String actual, String file) { String format(String source) { // TODO(devoncarew): Move this language version to a central location. // For tests, this version should match that of package:protoc_plugin. - final formatter = DartFormatter(languageVersion: Version(3, 6, 0)); + final formatter = DartFormatter(languageVersion: Version(3, 7, 0)); return formatter.format(source); } diff --git a/protoc_plugin/test/src/service_util.dart b/protoc_plugin/test/src/service_util.dart index 627254f3b..02f24a686 100644 --- a/protoc_plugin/test/src/service_util.dart +++ b/protoc_plugin/test/src/service_util.dart @@ -5,26 +5,31 @@ import 'package:protoc_plugin/src/gen/google/protobuf/descriptor.pb.dart'; ServiceDescriptorProto buildServiceDescriptor() { - final sd = ServiceDescriptorProto() - ..name = 'Test' - ..method.addAll([ - MethodDescriptorProto() - ..name = 'AMethod' - ..inputType = '.testpkg.SomeRequest' - ..outputType = '.testpkg.SomeReply', - MethodDescriptorProto() - ..name = 'AnotherMethod' - ..inputType = '.foo.bar.EmptyMessage' - ..outputType = '.foo.bar.AnotherReply', - ]); + final sd = + ServiceDescriptorProto() + ..name = 'Test' + ..method.addAll([ + MethodDescriptorProto() + ..name = 'AMethod' + ..inputType = '.testpkg.SomeRequest' + ..outputType = '.testpkg.SomeReply', + MethodDescriptorProto() + ..name = 'AnotherMethod' + ..inputType = '.foo.bar.EmptyMessage' + ..outputType = '.foo.bar.AnotherReply', + ]); return sd; } FileDescriptorProto buildFileDescriptor( - String package, String fileUri, List messages) { - final fd = FileDescriptorProto() - ..package = package - ..name = fileUri; + String package, + String fileUri, + List messages, +) { + final fd = + FileDescriptorProto() + ..package = package + ..name = fileUri; for (final name in messages) { final md = DescriptorProto()..name = name; diff --git a/protoc_plugin/test/src/test_util.dart b/protoc_plugin/test/src/test_util.dart index 464ec53b4..a48c2df77 100644 --- a/protoc_plugin/test/src/test_util.dart +++ b/protoc_plugin/test/src/test_util.dart @@ -43,16 +43,24 @@ void assertAllExtensionsSet(TestAllExtensions message) { expect(message.hasExtension(Unittest.optionalGroupExtension), isTrue); expect(message.hasExtension(Unittest.optionalNestedMessageExtension), isTrue); expect( - message.hasExtension(Unittest.optionalForeignMessageExtension), isTrue); + message.hasExtension(Unittest.optionalForeignMessageExtension), + isTrue, + ); expect(message.hasExtension(Unittest.optionalImportMessageExtension), isTrue); expect(message.getExtension(Unittest.optionalGroupExtension).hasA(), isTrue); - expect(message.getExtension(Unittest.optionalNestedMessageExtension).hasBb(), - isTrue); - expect(message.getExtension(Unittest.optionalForeignMessageExtension).hasC(), - isTrue); - expect(message.getExtension(Unittest.optionalImportMessageExtension).hasD(), - isTrue); + expect( + message.getExtension(Unittest.optionalNestedMessageExtension).hasBb(), + isTrue, + ); + expect( + message.getExtension(Unittest.optionalForeignMessageExtension).hasC(), + isTrue, + ); + expect( + message.getExtension(Unittest.optionalImportMessageExtension).hasD(), + isTrue, + ); expect(message.hasExtension(Unittest.optionalNestedEnumExtension), isTrue); expect(message.hasExtension(Unittest.optionalForeignEnumExtension), isTrue); @@ -69,28 +77,40 @@ void assertAllExtensionsSet(TestAllExtensions message) { expect(message.getExtension(Unittest.optionalSint64Extension), expect64(106)); expect(message.getExtension(Unittest.optionalFixed32Extension), 107); expect( - message.getExtension(Unittest.optionalFixed64Extension), expect64(108)); + message.getExtension(Unittest.optionalFixed64Extension), + expect64(108), + ); expect(message.getExtension(Unittest.optionalSfixed32Extension), 109); expect( - message.getExtension(Unittest.optionalSfixed64Extension), expect64(110)); + message.getExtension(Unittest.optionalSfixed64Extension), + expect64(110), + ); expect(message.getExtension(Unittest.optionalFloatExtension), 111.0); expect(message.getExtension(Unittest.optionalDoubleExtension), 112.0); expect(message.getExtension(Unittest.optionalBoolExtension), true); expect(message.getExtension(Unittest.optionalStringExtension), '115'); expect( - message.getExtension(Unittest.optionalBytesExtension), '116'.codeUnits); + message.getExtension(Unittest.optionalBytesExtension), + '116'.codeUnits, + ); expect(message.getExtension(Unittest.optionalGroupExtension).a, 117); expect(message.getExtension(Unittest.optionalNestedMessageExtension).bb, 118); expect(message.getExtension(Unittest.optionalForeignMessageExtension).c, 119); expect(message.getExtension(Unittest.optionalImportMessageExtension).d, 120); - expect(message.getExtension(Unittest.optionalNestedEnumExtension), - TestAllTypes_NestedEnum.BAZ); - expect(message.getExtension(Unittest.optionalForeignEnumExtension), - ForeignEnum.FOREIGN_BAZ); - expect(message.getExtension(Unittest.optionalImportEnumExtension), - ImportEnum.IMPORT_BAZ); + expect( + message.getExtension(Unittest.optionalNestedEnumExtension), + TestAllTypes_NestedEnum.BAZ, + ); + expect( + message.getExtension(Unittest.optionalForeignEnumExtension), + ForeignEnum.FOREIGN_BAZ, + ); + expect( + message.getExtension(Unittest.optionalImportEnumExtension), + ImportEnum.IMPORT_BAZ, + ); expect(message.getExtension(Unittest.optionalStringPieceExtension), '124'); expect(message.getExtension(Unittest.optionalCordExtension), '125'); @@ -115,11 +135,17 @@ void assertAllExtensionsSet(TestAllExtensions message) { expect(message.getExtension(Unittest.repeatedGroupExtension).length, 2); expect( - message.getExtension(Unittest.repeatedNestedMessageExtension).length, 2); + message.getExtension(Unittest.repeatedNestedMessageExtension).length, + 2, + ); expect( - message.getExtension(Unittest.repeatedForeignMessageExtension).length, 2); + message.getExtension(Unittest.repeatedForeignMessageExtension).length, + 2, + ); expect( - message.getExtension(Unittest.repeatedImportMessageExtension).length, 2); + message.getExtension(Unittest.repeatedImportMessageExtension).length, + 2, + ); expect(message.getExtension(Unittest.repeatedNestedEnumExtension).length, 2); expect(message.getExtension(Unittest.repeatedForeignEnumExtension).length, 2); expect(message.getExtension(Unittest.repeatedImportEnumExtension).length, 2); @@ -129,80 +155,128 @@ void assertAllExtensionsSet(TestAllExtensions message) { expect(message.getExtension(Unittest.repeatedInt32Extension)[0], 201); expect( - message.getExtension(Unittest.repeatedInt64Extension)[0], expect64(202)); + message.getExtension(Unittest.repeatedInt64Extension)[0], + expect64(202), + ); expect(message.getExtension(Unittest.repeatedUint32Extension)[0], 203); expect( - message.getExtension(Unittest.repeatedUint64Extension)[0], expect64(204)); + message.getExtension(Unittest.repeatedUint64Extension)[0], + expect64(204), + ); expect(message.getExtension(Unittest.repeatedSint32Extension)[0], 205); expect( - message.getExtension(Unittest.repeatedSint64Extension)[0], expect64(206)); + message.getExtension(Unittest.repeatedSint64Extension)[0], + expect64(206), + ); expect(message.getExtension(Unittest.repeatedFixed32Extension)[0], 207); - expect(message.getExtension(Unittest.repeatedFixed64Extension)[0], - expect64(208)); + expect( + message.getExtension(Unittest.repeatedFixed64Extension)[0], + expect64(208), + ); expect(message.getExtension(Unittest.repeatedSfixed32Extension)[0], 209); - expect(message.getExtension(Unittest.repeatedSfixed64Extension)[0], - expect64(210)); + expect( + message.getExtension(Unittest.repeatedSfixed64Extension)[0], + expect64(210), + ); expect(message.getExtension(Unittest.repeatedFloatExtension)[0], 211.0); expect(message.getExtension(Unittest.repeatedDoubleExtension)[0], 212.0); expect(message.getExtension(Unittest.repeatedBoolExtension)[0], true); expect(message.getExtension(Unittest.repeatedStringExtension)[0], '215'); - expect(message.getExtension(Unittest.repeatedBytesExtension)[0], - '216'.codeUnits); + expect( + message.getExtension(Unittest.repeatedBytesExtension)[0], + '216'.codeUnits, + ); expect(message.getExtension(Unittest.repeatedGroupExtension)[0].a, 217); expect( - message.getExtension(Unittest.repeatedNestedMessageExtension)[0].bb, 218); + message.getExtension(Unittest.repeatedNestedMessageExtension)[0].bb, + 218, + ); expect( - message.getExtension(Unittest.repeatedForeignMessageExtension)[0].c, 219); + message.getExtension(Unittest.repeatedForeignMessageExtension)[0].c, + 219, + ); expect( - message.getExtension(Unittest.repeatedImportMessageExtension)[0].d, 220); + message.getExtension(Unittest.repeatedImportMessageExtension)[0].d, + 220, + ); - expect(message.getExtension(Unittest.repeatedNestedEnumExtension)[0], - TestAllTypes_NestedEnum.BAR); - expect(message.getExtension(Unittest.repeatedForeignEnumExtension)[0], - ForeignEnum.FOREIGN_BAR); - expect(message.getExtension(Unittest.repeatedImportEnumExtension)[0], - ImportEnum.IMPORT_BAR); + expect( + message.getExtension(Unittest.repeatedNestedEnumExtension)[0], + TestAllTypes_NestedEnum.BAR, + ); + expect( + message.getExtension(Unittest.repeatedForeignEnumExtension)[0], + ForeignEnum.FOREIGN_BAR, + ); + expect( + message.getExtension(Unittest.repeatedImportEnumExtension)[0], + ImportEnum.IMPORT_BAR, + ); expect(message.getExtension(Unittest.repeatedStringPieceExtension)[0], '224'); expect(message.getExtension(Unittest.repeatedCordExtension)[0], '225'); expect(message.getExtension(Unittest.repeatedInt32Extension)[1], 301); expect( - message.getExtension(Unittest.repeatedInt64Extension)[1], expect64(302)); + message.getExtension(Unittest.repeatedInt64Extension)[1], + expect64(302), + ); expect(message.getExtension(Unittest.repeatedUint32Extension)[1], 303); expect( - message.getExtension(Unittest.repeatedUint64Extension)[1], expect64(304)); + message.getExtension(Unittest.repeatedUint64Extension)[1], + expect64(304), + ); expect(message.getExtension(Unittest.repeatedSint32Extension)[1], 305); expect( - message.getExtension(Unittest.repeatedSint64Extension)[1], expect64(306)); + message.getExtension(Unittest.repeatedSint64Extension)[1], + expect64(306), + ); expect(message.getExtension(Unittest.repeatedFixed32Extension)[1], 307); - expect(message.getExtension(Unittest.repeatedFixed64Extension)[1], - expect64(308)); + expect( + message.getExtension(Unittest.repeatedFixed64Extension)[1], + expect64(308), + ); expect(message.getExtension(Unittest.repeatedSfixed32Extension)[1], 309); - expect(message.getExtension(Unittest.repeatedSfixed64Extension)[1], - expect64(310)); + expect( + message.getExtension(Unittest.repeatedSfixed64Extension)[1], + expect64(310), + ); expect(message.getExtension(Unittest.repeatedFloatExtension)[1], 311.0); expect(message.getExtension(Unittest.repeatedDoubleExtension)[1], 312.0); expect(message.getExtension(Unittest.repeatedBoolExtension)[1], false); expect(message.getExtension(Unittest.repeatedStringExtension)[1], '315'); - expect(message.getExtension(Unittest.repeatedBytesExtension)[1], - '316'.codeUnits); + expect( + message.getExtension(Unittest.repeatedBytesExtension)[1], + '316'.codeUnits, + ); expect(message.getExtension(Unittest.repeatedGroupExtension)[1].a, 317); expect( - message.getExtension(Unittest.repeatedNestedMessageExtension)[1].bb, 318); + message.getExtension(Unittest.repeatedNestedMessageExtension)[1].bb, + 318, + ); expect( - message.getExtension(Unittest.repeatedForeignMessageExtension)[1].c, 319); + message.getExtension(Unittest.repeatedForeignMessageExtension)[1].c, + 319, + ); expect( - message.getExtension(Unittest.repeatedImportMessageExtension)[1].d, 320); + message.getExtension(Unittest.repeatedImportMessageExtension)[1].d, + 320, + ); - expect(message.getExtension(Unittest.repeatedNestedEnumExtension)[1], - TestAllTypes_NestedEnum.BAZ); - expect(message.getExtension(Unittest.repeatedForeignEnumExtension)[1], - ForeignEnum.FOREIGN_BAZ); - expect(message.getExtension(Unittest.repeatedImportEnumExtension)[1], - ImportEnum.IMPORT_BAZ); + expect( + message.getExtension(Unittest.repeatedNestedEnumExtension)[1], + TestAllTypes_NestedEnum.BAZ, + ); + expect( + message.getExtension(Unittest.repeatedForeignEnumExtension)[1], + ForeignEnum.FOREIGN_BAZ, + ); + expect( + message.getExtension(Unittest.repeatedImportEnumExtension)[1], + ImportEnum.IMPORT_BAZ, + ); expect(message.getExtension(Unittest.repeatedStringPieceExtension)[1], '324'); expect(message.getExtension(Unittest.repeatedCordExtension)[1], '325'); @@ -241,19 +315,27 @@ void assertAllExtensionsSet(TestAllExtensions message) { expect(message.getExtension(Unittest.defaultFixed64Extension), expect64(408)); expect(message.getExtension(Unittest.defaultSfixed32Extension), 409); expect( - message.getExtension(Unittest.defaultSfixed64Extension), expect64(410)); + message.getExtension(Unittest.defaultSfixed64Extension), + expect64(410), + ); expect(message.getExtension(Unittest.defaultFloatExtension), 411.0); expect(message.getExtension(Unittest.defaultDoubleExtension), 412.0); expect(message.getExtension(Unittest.defaultBoolExtension), false); expect(message.getExtension(Unittest.defaultStringExtension), '415'); expect(message.getExtension(Unittest.defaultBytesExtension), '416'.codeUnits); - expect(message.getExtension(Unittest.defaultNestedEnumExtension), - TestAllTypes_NestedEnum.FOO); - expect(message.getExtension(Unittest.defaultForeignEnumExtension), - ForeignEnum.FOREIGN_FOO); - expect(message.getExtension(Unittest.defaultImportEnumExtension), - ImportEnum.IMPORT_FOO); + expect( + message.getExtension(Unittest.defaultNestedEnumExtension), + TestAllTypes_NestedEnum.FOO, + ); + expect( + message.getExtension(Unittest.defaultForeignEnumExtension), + ForeignEnum.FOREIGN_FOO, + ); + expect( + message.getExtension(Unittest.defaultImportEnumExtension), + ImportEnum.IMPORT_FOO, + ); expect(message.getExtension(Unittest.defaultStringPieceExtension), '424'); expect(message.getExtension(Unittest.defaultCordExtension), '425'); @@ -618,11 +700,17 @@ void assertExtensionsClear(TestAllExtensions message) { expect(message.hasExtension(Unittest.optionalGroupExtension), isFalse); expect( - message.hasExtension(Unittest.optionalNestedMessageExtension), isFalse); + message.hasExtension(Unittest.optionalNestedMessageExtension), + isFalse, + ); expect( - message.hasExtension(Unittest.optionalForeignMessageExtension), isFalse); + message.hasExtension(Unittest.optionalForeignMessageExtension), + isFalse, + ); expect( - message.hasExtension(Unittest.optionalImportMessageExtension), isFalse); + message.hasExtension(Unittest.optionalImportMessageExtension), + isFalse, + ); expect(message.hasExtension(Unittest.optionalNestedEnumExtension), isFalse); expect(message.hasExtension(Unittest.optionalForeignEnumExtension), isFalse); @@ -650,12 +738,18 @@ void assertExtensionsClear(TestAllExtensions message) { // Embedded messages should also be clear. expect(message.getExtension(Unittest.optionalGroupExtension).hasA(), isFalse); - expect(message.getExtension(Unittest.optionalNestedMessageExtension).hasBb(), - isFalse); - expect(message.getExtension(Unittest.optionalForeignMessageExtension).hasC(), - isFalse); - expect(message.getExtension(Unittest.optionalImportMessageExtension).hasD(), - isFalse); + expect( + message.getExtension(Unittest.optionalNestedMessageExtension).hasBb(), + isFalse, + ); + expect( + message.getExtension(Unittest.optionalForeignMessageExtension).hasC(), + isFalse, + ); + expect( + message.getExtension(Unittest.optionalImportMessageExtension).hasD(), + isFalse, + ); expect(message.getExtension(Unittest.optionalGroupExtension).a, 0); expect(message.getExtension(Unittest.optionalNestedMessageExtension).bb, 0); @@ -663,12 +757,18 @@ void assertExtensionsClear(TestAllExtensions message) { expect(message.getExtension(Unittest.optionalImportMessageExtension).d, 0); // Enums without defaults are set to the first value in the enum. - expect(message.getExtension(Unittest.optionalNestedEnumExtension), - TestAllTypes_NestedEnum.FOO); - expect(message.getExtension(Unittest.optionalForeignEnumExtension), - ForeignEnum.FOREIGN_FOO); - expect(message.getExtension(Unittest.optionalImportEnumExtension), - ImportEnum.IMPORT_FOO); + expect( + message.getExtension(Unittest.optionalNestedEnumExtension), + TestAllTypes_NestedEnum.FOO, + ); + expect( + message.getExtension(Unittest.optionalForeignEnumExtension), + ForeignEnum.FOREIGN_FOO, + ); + expect( + message.getExtension(Unittest.optionalImportEnumExtension), + ImportEnum.IMPORT_FOO, + ); expect(message.getExtension(Unittest.optionalStringPieceExtension), ''); expect(message.getExtension(Unittest.optionalCordExtension), ''); @@ -692,11 +792,17 @@ void assertExtensionsClear(TestAllExtensions message) { expect(message.getExtension(Unittest.repeatedGroupExtension).length, 0); expect( - message.getExtension(Unittest.repeatedNestedMessageExtension).length, 0); + message.getExtension(Unittest.repeatedNestedMessageExtension).length, + 0, + ); expect( - message.getExtension(Unittest.repeatedForeignMessageExtension).length, 0); + message.getExtension(Unittest.repeatedForeignMessageExtension).length, + 0, + ); expect( - message.getExtension(Unittest.repeatedImportMessageExtension).length, 0); + message.getExtension(Unittest.repeatedImportMessageExtension).length, + 0, + ); expect(message.getExtension(Unittest.repeatedNestedEnumExtension).length, 0); expect(message.getExtension(Unittest.repeatedForeignEnumExtension).length, 0); expect(message.getExtension(Unittest.repeatedImportEnumExtension).length, 0); @@ -723,11 +829,17 @@ void assertExtensionsClear(TestAllExtensions message) { expect(message.getExtension(Unittest.repeatedGroupExtension).length, 0); expect( - message.getExtension(Unittest.repeatedNestedMessageExtension).length, 0); + message.getExtension(Unittest.repeatedNestedMessageExtension).length, + 0, + ); expect( - message.getExtension(Unittest.repeatedForeignMessageExtension).length, 0); + message.getExtension(Unittest.repeatedForeignMessageExtension).length, + 0, + ); expect( - message.getExtension(Unittest.repeatedImportMessageExtension).length, 0); + message.getExtension(Unittest.repeatedImportMessageExtension).length, + 0, + ); expect(message.getExtension(Unittest.repeatedNestedEnumExtension).length, 0); expect(message.getExtension(Unittest.repeatedForeignEnumExtension).length, 0); expect(message.getExtension(Unittest.repeatedImportEnumExtension).length, 0); @@ -770,20 +882,30 @@ void assertExtensionsClear(TestAllExtensions message) { expect(message.getExtension(Unittest.defaultFixed64Extension), expect64(48)); expect(message.getExtension(Unittest.defaultSfixed32Extension), 49); expect( - message.getExtension(Unittest.defaultSfixed64Extension), expect64(-50)); + message.getExtension(Unittest.defaultSfixed64Extension), + expect64(-50), + ); expect(message.getExtension(Unittest.defaultFloatExtension), 51.5); expect(message.getExtension(Unittest.defaultDoubleExtension), 52e3); expect(message.getExtension(Unittest.defaultBoolExtension), true); expect(message.getExtension(Unittest.defaultStringExtension), 'hello'); expect( - message.getExtension(Unittest.defaultBytesExtension), 'world'.codeUnits); + message.getExtension(Unittest.defaultBytesExtension), + 'world'.codeUnits, + ); - expect(message.getExtension(Unittest.defaultNestedEnumExtension), - TestAllTypes_NestedEnum.BAR); - expect(message.getExtension(Unittest.defaultForeignEnumExtension), - ForeignEnum.FOREIGN_BAR); - expect(message.getExtension(Unittest.defaultImportEnumExtension), - ImportEnum.IMPORT_BAR); + expect( + message.getExtension(Unittest.defaultNestedEnumExtension), + TestAllTypes_NestedEnum.BAR, + ); + expect( + message.getExtension(Unittest.defaultForeignEnumExtension), + ForeignEnum.FOREIGN_BAR, + ); + expect( + message.getExtension(Unittest.defaultImportEnumExtension), + ImportEnum.IMPORT_BAR, + ); expect(message.getExtension(Unittest.defaultStringPieceExtension), 'abc'); expect(message.getExtension(Unittest.defaultCordExtension), '123'); @@ -808,40 +930,60 @@ void assertPackedExtensionsSet(TestPackedExtensions message) { expect(message.getExtension(Unittest.packedInt64Extension)[0], expect64(602)); expect(message.getExtension(Unittest.packedUint32Extension)[0], 603); expect( - message.getExtension(Unittest.packedUint64Extension)[0], expect64(604)); + message.getExtension(Unittest.packedUint64Extension)[0], + expect64(604), + ); expect(message.getExtension(Unittest.packedSint32Extension)[0], 605); expect( - message.getExtension(Unittest.packedSint64Extension)[0], expect64(606)); + message.getExtension(Unittest.packedSint64Extension)[0], + expect64(606), + ); expect(message.getExtension(Unittest.packedFixed32Extension)[0], 607); expect( - message.getExtension(Unittest.packedFixed64Extension)[0], expect64(608)); + message.getExtension(Unittest.packedFixed64Extension)[0], + expect64(608), + ); expect(message.getExtension(Unittest.packedSfixed32Extension)[0], 609); expect( - message.getExtension(Unittest.packedSfixed64Extension)[0], expect64(610)); + message.getExtension(Unittest.packedSfixed64Extension)[0], + expect64(610), + ); expect(message.getExtension(Unittest.packedFloatExtension)[0], 611.0); expect(message.getExtension(Unittest.packedDoubleExtension)[0], 612.0); expect(message.getExtension(Unittest.packedBoolExtension)[0], true); - expect(message.getExtension(Unittest.packedEnumExtension)[0], - ForeignEnum.FOREIGN_BAR); + expect( + message.getExtension(Unittest.packedEnumExtension)[0], + ForeignEnum.FOREIGN_BAR, + ); expect(message.getExtension(Unittest.packedInt32Extension)[1], 701); expect(message.getExtension(Unittest.packedInt64Extension)[1], expect64(702)); expect(message.getExtension(Unittest.packedUint32Extension)[1], 703); expect( - message.getExtension(Unittest.packedUint64Extension)[1], expect64(704)); + message.getExtension(Unittest.packedUint64Extension)[1], + expect64(704), + ); expect(message.getExtension(Unittest.packedSint32Extension)[1], 705); expect( - message.getExtension(Unittest.packedSint64Extension)[1], expect64(706)); + message.getExtension(Unittest.packedSint64Extension)[1], + expect64(706), + ); expect(message.getExtension(Unittest.packedFixed32Extension)[1], 707); expect( - message.getExtension(Unittest.packedFixed64Extension)[1], expect64(708)); + message.getExtension(Unittest.packedFixed64Extension)[1], + expect64(708), + ); expect(message.getExtension(Unittest.packedSfixed32Extension)[1], 709); expect( - message.getExtension(Unittest.packedSfixed64Extension)[1], expect64(710)); + message.getExtension(Unittest.packedSfixed64Extension)[1], + expect64(710), + ); expect(message.getExtension(Unittest.packedFloatExtension)[1], 711.0); expect(message.getExtension(Unittest.packedDoubleExtension)[1], 712.0); expect(message.getExtension(Unittest.packedBoolExtension)[1], false); - expect(message.getExtension(Unittest.packedEnumExtension)[1], - ForeignEnum.FOREIGN_BAZ); + expect( + message.getExtension(Unittest.packedEnumExtension)[1], + ForeignEnum.FOREIGN_BAZ, + ); } // Assert (using expect} that all fields of [message] are set to the values @@ -911,16 +1053,24 @@ void assertRepeatedExtensionsModified(TestAllExtensions message) { expect(message.hasExtension(Unittest.optionalGroupExtension), isTrue); expect(message.hasExtension(Unittest.optionalNestedMessageExtension), isTrue); expect( - message.hasExtension(Unittest.optionalForeignMessageExtension), isTrue); + message.hasExtension(Unittest.optionalForeignMessageExtension), + isTrue, + ); expect(message.hasExtension(Unittest.optionalImportMessageExtension), isTrue); expect(message.getExtension(Unittest.optionalGroupExtension).hasA(), isTrue); - expect(message.getExtension(Unittest.optionalNestedMessageExtension).hasBb(), - isTrue); - expect(message.getExtension(Unittest.optionalForeignMessageExtension).hasC(), - isTrue); - expect(message.getExtension(Unittest.optionalImportMessageExtension).hasD(), - isTrue); + expect( + message.getExtension(Unittest.optionalNestedMessageExtension).hasBb(), + isTrue, + ); + expect( + message.getExtension(Unittest.optionalForeignMessageExtension).hasC(), + isTrue, + ); + expect( + message.getExtension(Unittest.optionalImportMessageExtension).hasD(), + isTrue, + ); expect(message.hasExtension(Unittest.optionalNestedEnumExtension), isTrue); expect(message.hasExtension(Unittest.optionalForeignEnumExtension), isTrue); @@ -937,28 +1087,40 @@ void assertRepeatedExtensionsModified(TestAllExtensions message) { expect(message.getExtension(Unittest.optionalSint64Extension), expect64(106)); expect(message.getExtension(Unittest.optionalFixed32Extension), 107); expect( - message.getExtension(Unittest.optionalFixed64Extension), expect64(108)); + message.getExtension(Unittest.optionalFixed64Extension), + expect64(108), + ); expect(message.getExtension(Unittest.optionalSfixed32Extension), 109); expect( - message.getExtension(Unittest.optionalSfixed64Extension), expect64(110)); + message.getExtension(Unittest.optionalSfixed64Extension), + expect64(110), + ); expect(message.getExtension(Unittest.optionalFloatExtension), 111.0); expect(message.getExtension(Unittest.optionalDoubleExtension), 112.0); expect(message.getExtension(Unittest.optionalBoolExtension), true); expect(message.getExtension(Unittest.optionalStringExtension), '115'); expect( - message.getExtension(Unittest.optionalBytesExtension), '116'.codeUnits); + message.getExtension(Unittest.optionalBytesExtension), + '116'.codeUnits, + ); expect(message.getExtension(Unittest.optionalGroupExtension).a, 117); expect(message.getExtension(Unittest.optionalNestedMessageExtension).bb, 118); expect(message.getExtension(Unittest.optionalForeignMessageExtension).c, 119); expect(message.getExtension(Unittest.optionalImportMessageExtension).d, 120); - expect(message.getExtension(Unittest.optionalNestedEnumExtension), - TestAllTypes_NestedEnum.BAZ); - expect(message.getExtension(Unittest.optionalForeignEnumExtension), - ForeignEnum.FOREIGN_BAZ); - expect(message.getExtension(Unittest.optionalImportEnumExtension), - ImportEnum.IMPORT_BAZ); + expect( + message.getExtension(Unittest.optionalNestedEnumExtension), + TestAllTypes_NestedEnum.BAZ, + ); + expect( + message.getExtension(Unittest.optionalForeignEnumExtension), + ForeignEnum.FOREIGN_BAZ, + ); + expect( + message.getExtension(Unittest.optionalImportEnumExtension), + ImportEnum.IMPORT_BAZ, + ); expect(message.getExtension(Unittest.optionalStringPieceExtension), '124'); expect(message.getExtension(Unittest.optionalCordExtension), '125'); @@ -983,11 +1145,17 @@ void assertRepeatedExtensionsModified(TestAllExtensions message) { expect(message.getExtension(Unittest.repeatedGroupExtension).length, 2); expect( - message.getExtension(Unittest.repeatedNestedMessageExtension).length, 2); + message.getExtension(Unittest.repeatedNestedMessageExtension).length, + 2, + ); expect( - message.getExtension(Unittest.repeatedForeignMessageExtension).length, 2); + message.getExtension(Unittest.repeatedForeignMessageExtension).length, + 2, + ); expect( - message.getExtension(Unittest.repeatedImportMessageExtension).length, 2); + message.getExtension(Unittest.repeatedImportMessageExtension).length, + 2, + ); expect(message.getExtension(Unittest.repeatedNestedEnumExtension).length, 2); expect(message.getExtension(Unittest.repeatedForeignEnumExtension).length, 2); expect(message.getExtension(Unittest.repeatedImportEnumExtension).length, 2); @@ -997,80 +1165,128 @@ void assertRepeatedExtensionsModified(TestAllExtensions message) { expect(message.getExtension(Unittest.repeatedInt32Extension)[0], 201); expect( - message.getExtension(Unittest.repeatedInt64Extension)[0], expect64(202)); + message.getExtension(Unittest.repeatedInt64Extension)[0], + expect64(202), + ); expect(message.getExtension(Unittest.repeatedUint32Extension)[0], 203); expect( - message.getExtension(Unittest.repeatedUint64Extension)[0], expect64(204)); + message.getExtension(Unittest.repeatedUint64Extension)[0], + expect64(204), + ); expect(message.getExtension(Unittest.repeatedSint32Extension)[0], 205); expect( - message.getExtension(Unittest.repeatedSint64Extension)[0], expect64(206)); + message.getExtension(Unittest.repeatedSint64Extension)[0], + expect64(206), + ); expect(message.getExtension(Unittest.repeatedFixed32Extension)[0], 207); - expect(message.getExtension(Unittest.repeatedFixed64Extension)[0], - expect64(208)); + expect( + message.getExtension(Unittest.repeatedFixed64Extension)[0], + expect64(208), + ); expect(message.getExtension(Unittest.repeatedSfixed32Extension)[0], 209); - expect(message.getExtension(Unittest.repeatedSfixed64Extension)[0], - expect64(210)); + expect( + message.getExtension(Unittest.repeatedSfixed64Extension)[0], + expect64(210), + ); expect(message.getExtension(Unittest.repeatedFloatExtension)[0], 211.0); expect(message.getExtension(Unittest.repeatedDoubleExtension)[0], 212.0); expect(message.getExtension(Unittest.repeatedBoolExtension)[0], true); expect(message.getExtension(Unittest.repeatedStringExtension)[0], '215'); - expect(message.getExtension(Unittest.repeatedBytesExtension)[0], - '216'.codeUnits); + expect( + message.getExtension(Unittest.repeatedBytesExtension)[0], + '216'.codeUnits, + ); expect(message.getExtension(Unittest.repeatedGroupExtension)[0].a, 217); expect( - message.getExtension(Unittest.repeatedNestedMessageExtension)[0].bb, 218); + message.getExtension(Unittest.repeatedNestedMessageExtension)[0].bb, + 218, + ); expect( - message.getExtension(Unittest.repeatedForeignMessageExtension)[0].c, 219); + message.getExtension(Unittest.repeatedForeignMessageExtension)[0].c, + 219, + ); expect( - message.getExtension(Unittest.repeatedImportMessageExtension)[0].d, 220); + message.getExtension(Unittest.repeatedImportMessageExtension)[0].d, + 220, + ); - expect(message.getExtension(Unittest.repeatedNestedEnumExtension)[0], - TestAllTypes_NestedEnum.BAR); - expect(message.getExtension(Unittest.repeatedForeignEnumExtension)[0], - ForeignEnum.FOREIGN_BAR); - expect(message.getExtension(Unittest.repeatedImportEnumExtension)[0], - ImportEnum.IMPORT_BAR); + expect( + message.getExtension(Unittest.repeatedNestedEnumExtension)[0], + TestAllTypes_NestedEnum.BAR, + ); + expect( + message.getExtension(Unittest.repeatedForeignEnumExtension)[0], + ForeignEnum.FOREIGN_BAR, + ); + expect( + message.getExtension(Unittest.repeatedImportEnumExtension)[0], + ImportEnum.IMPORT_BAR, + ); expect(message.getExtension(Unittest.repeatedStringPieceExtension)[0], '224'); expect(message.getExtension(Unittest.repeatedCordExtension)[0], '225'); expect(message.getExtension(Unittest.repeatedInt32Extension)[1], 501); expect( - message.getExtension(Unittest.repeatedInt64Extension)[1], expect64(502)); + message.getExtension(Unittest.repeatedInt64Extension)[1], + expect64(502), + ); expect(message.getExtension(Unittest.repeatedUint32Extension)[1], 503); expect( - message.getExtension(Unittest.repeatedUint64Extension)[1], expect64(504)); + message.getExtension(Unittest.repeatedUint64Extension)[1], + expect64(504), + ); expect(message.getExtension(Unittest.repeatedSint32Extension)[1], 505); expect( - message.getExtension(Unittest.repeatedSint64Extension)[1], expect64(506)); + message.getExtension(Unittest.repeatedSint64Extension)[1], + expect64(506), + ); expect(message.getExtension(Unittest.repeatedFixed32Extension)[1], 507); - expect(message.getExtension(Unittest.repeatedFixed64Extension)[1], - expect64(508)); + expect( + message.getExtension(Unittest.repeatedFixed64Extension)[1], + expect64(508), + ); expect(message.getExtension(Unittest.repeatedSfixed32Extension)[1], 509); - expect(message.getExtension(Unittest.repeatedSfixed64Extension)[1], - expect64(510)); + expect( + message.getExtension(Unittest.repeatedSfixed64Extension)[1], + expect64(510), + ); expect(message.getExtension(Unittest.repeatedFloatExtension)[1], 511.0); expect(message.getExtension(Unittest.repeatedDoubleExtension)[1], 512.0); expect(message.getExtension(Unittest.repeatedBoolExtension)[1], true); expect(message.getExtension(Unittest.repeatedStringExtension)[1], '515'); - expect(message.getExtension(Unittest.repeatedBytesExtension)[1], - '516'.codeUnits); + expect( + message.getExtension(Unittest.repeatedBytesExtension)[1], + '516'.codeUnits, + ); expect(message.getExtension(Unittest.repeatedGroupExtension)[1].a, 517); expect( - message.getExtension(Unittest.repeatedNestedMessageExtension)[1].bb, 518); + message.getExtension(Unittest.repeatedNestedMessageExtension)[1].bb, + 518, + ); expect( - message.getExtension(Unittest.repeatedForeignMessageExtension)[1].c, 519); + message.getExtension(Unittest.repeatedForeignMessageExtension)[1].c, + 519, + ); expect( - message.getExtension(Unittest.repeatedImportMessageExtension)[1].d, 520); + message.getExtension(Unittest.repeatedImportMessageExtension)[1].d, + 520, + ); - expect(message.getExtension(Unittest.repeatedNestedEnumExtension)[1], - TestAllTypes_NestedEnum.FOO); - expect(message.getExtension(Unittest.repeatedForeignEnumExtension)[1], - ForeignEnum.FOREIGN_FOO); - expect(message.getExtension(Unittest.repeatedImportEnumExtension)[1], - ImportEnum.IMPORT_FOO); + expect( + message.getExtension(Unittest.repeatedNestedEnumExtension)[1], + TestAllTypes_NestedEnum.FOO, + ); + expect( + message.getExtension(Unittest.repeatedForeignEnumExtension)[1], + ForeignEnum.FOREIGN_FOO, + ); + expect( + message.getExtension(Unittest.repeatedImportEnumExtension)[1], + ImportEnum.IMPORT_FOO, + ); expect(message.getExtension(Unittest.repeatedStringPieceExtension)[1], '524'); expect(message.getExtension(Unittest.repeatedCordExtension)[1], '525'); @@ -1110,19 +1326,27 @@ void assertRepeatedExtensionsModified(TestAllExtensions message) { expect(message.getExtension(Unittest.defaultFixed64Extension), expect64(408)); expect(message.getExtension(Unittest.defaultSfixed32Extension), 409); expect( - message.getExtension(Unittest.defaultSfixed64Extension), expect64(410)); + message.getExtension(Unittest.defaultSfixed64Extension), + expect64(410), + ); expect(message.getExtension(Unittest.defaultFloatExtension), 411.0); expect(message.getExtension(Unittest.defaultDoubleExtension), 412.0); expect(message.getExtension(Unittest.defaultBoolExtension), false); expect(message.getExtension(Unittest.defaultStringExtension), '415'); expect(message.getExtension(Unittest.defaultBytesExtension), '416'.codeUnits); - expect(message.getExtension(Unittest.defaultNestedEnumExtension), - TestAllTypes_NestedEnum.FOO); - expect(message.getExtension(Unittest.defaultForeignEnumExtension), - ForeignEnum.FOREIGN_FOO); - expect(message.getExtension(Unittest.defaultImportEnumExtension), - ImportEnum.IMPORT_FOO); + expect( + message.getExtension(Unittest.defaultNestedEnumExtension), + TestAllTypes_NestedEnum.FOO, + ); + expect( + message.getExtension(Unittest.defaultForeignEnumExtension), + ForeignEnum.FOREIGN_FOO, + ); + expect( + message.getExtension(Unittest.defaultImportEnumExtension), + ImportEnum.IMPORT_FOO, + ); expect(message.getExtension(Unittest.defaultStringPieceExtension), '424'); expect(message.getExtension(Unittest.defaultCordExtension), '425'); @@ -1429,11 +1653,17 @@ void setAllExtensions(TestAllExtensions message) { message.setExtension(Unittest.optionalImportMessageExtension, msg4); message.setExtension( - Unittest.optionalNestedEnumExtension, TestAllTypes_NestedEnum.BAZ); + Unittest.optionalNestedEnumExtension, + TestAllTypes_NestedEnum.BAZ, + ); message.setExtension( - Unittest.optionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); + Unittest.optionalForeignEnumExtension, + ForeignEnum.FOREIGN_BAZ, + ); message.setExtension( - Unittest.optionalImportEnumExtension, ImportEnum.IMPORT_BAZ); + Unittest.optionalImportEnumExtension, + ImportEnum.IMPORT_BAZ, + ); message.setExtension(Unittest.optionalStringPieceExtension, '124'); message.setExtension(Unittest.optionalCordExtension, '125'); @@ -1473,11 +1703,17 @@ void setAllExtensions(TestAllExtensions message) { message.addExtension(Unittest.repeatedImportMessageExtension, msg8); message.addExtension( - Unittest.repeatedNestedEnumExtension, TestAllTypes_NestedEnum.BAR); + Unittest.repeatedNestedEnumExtension, + TestAllTypes_NestedEnum.BAR, + ); message.addExtension( - Unittest.repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAR); + Unittest.repeatedForeignEnumExtension, + ForeignEnum.FOREIGN_BAR, + ); message.addExtension( - Unittest.repeatedImportEnumExtension, ImportEnum.IMPORT_BAR); + Unittest.repeatedImportEnumExtension, + ImportEnum.IMPORT_BAR, + ); message.addExtension(Unittest.repeatedStringPieceExtension, '224'); message.addExtension(Unittest.repeatedCordExtension, '225'); @@ -1516,11 +1752,17 @@ void setAllExtensions(TestAllExtensions message) { message.addExtension(Unittest.repeatedImportMessageExtension, msg12); message.addExtension( - Unittest.repeatedNestedEnumExtension, TestAllTypes_NestedEnum.BAZ); + Unittest.repeatedNestedEnumExtension, + TestAllTypes_NestedEnum.BAZ, + ); message.addExtension( - Unittest.repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); + Unittest.repeatedForeignEnumExtension, + ForeignEnum.FOREIGN_BAZ, + ); message.addExtension( - Unittest.repeatedImportEnumExtension, ImportEnum.IMPORT_BAZ); + Unittest.repeatedImportEnumExtension, + ImportEnum.IMPORT_BAZ, + ); message.addExtension(Unittest.repeatedStringPieceExtension, '324'); message.addExtension(Unittest.repeatedCordExtension, '325'); @@ -1544,11 +1786,17 @@ void setAllExtensions(TestAllExtensions message) { message.setExtension(Unittest.defaultBytesExtension, '416'.codeUnits); message.setExtension( - Unittest.defaultNestedEnumExtension, TestAllTypes_NestedEnum.FOO); + Unittest.defaultNestedEnumExtension, + TestAllTypes_NestedEnum.FOO, + ); message.setExtension( - Unittest.defaultForeignEnumExtension, ForeignEnum.FOREIGN_FOO); + Unittest.defaultForeignEnumExtension, + ForeignEnum.FOREIGN_FOO, + ); message.setExtension( - Unittest.defaultImportEnumExtension, ImportEnum.IMPORT_FOO); + Unittest.defaultImportEnumExtension, + ImportEnum.IMPORT_FOO, + ); message.setExtension(Unittest.defaultStringPieceExtension, '424'); message.setExtension(Unittest.defaultCordExtension, '425'); diff --git a/protoc_plugin/test/timestamp_test.dart b/protoc_plugin/test/timestamp_test.dart index 7fec06314..d039bd481 100644 --- a/protoc_plugin/test/timestamp_test.dart +++ b/protoc_plugin/test/timestamp_test.dart @@ -9,9 +9,10 @@ import 'gen/google/protobuf/timestamp.pb.dart'; void main() { test('timestamp -> datetime -> timestamp', () { - final timestamp = Timestamp() - ..seconds = Int64(1550225928) - ..nanos = 12345000; + final timestamp = + Timestamp() + ..seconds = Int64(1550225928) + ..nanos = 12345000; expect(Timestamp.fromDateTime(timestamp.toDateTime()), timestamp); }); @@ -24,13 +25,16 @@ void main() { }); test('negative Timestamp', () { - final secondBeforeEpoch = Timestamp() - ..seconds = Int64(-1) - ..nanos = 1000000; + final secondBeforeEpoch = + Timestamp() + ..seconds = Int64(-1) + ..nanos = 1000000; final dateTime = DateTime.fromMillisecondsSinceEpoch(-999, isUtc: true); - expect(secondBeforeEpoch.toDateTime().millisecondsSinceEpoch, - dateTime.millisecondsSinceEpoch); + expect( + secondBeforeEpoch.toDateTime().millisecondsSinceEpoch, + dateTime.millisecondsSinceEpoch, + ); expect(secondBeforeEpoch.toDateTime(), dateTime); expect(Timestamp.fromDateTime(dateTime).nanos, 1000000); expect(Timestamp.fromDateTime(dateTime).seconds, Int64(-1)); diff --git a/protoc_plugin/test/to_builder_test.dart b/protoc_plugin/test/to_builder_test.dart index 28545f5d5..37892692e 100644 --- a/protoc_plugin/test/to_builder_test.dart +++ b/protoc_plugin/test/to_builder_test.dart @@ -13,36 +13,51 @@ import 'gen/google/protobuf/unittest.pb.dart'; void main() { group('frozen and tobuilder', () { - final original = Outer() - ..inner = (Inner()..value = 'foo') - ..inners.add(Inner()..value = 'repeatedInner') - ..setExtension(FooExt.inner, Inner()..value = 'extension') - ..getExtension(FooExt.inners).add(Inner()..value = 'repeatedExtension') - ..freeze(); + final original = + Outer() + ..inner = (Inner()..value = 'foo') + ..inners.add(Inner()..value = 'repeatedInner') + ..setExtension(FooExt.inner, Inner()..value = 'extension') + ..getExtension( + FooExt.inners, + ).add(Inner()..value = 'repeatedExtension') + ..freeze(); test('can read extensions', () { expect(original.getExtension(FooExt.inner).value, 'extension'); expect( - original.getExtension(FooExt.inners)[0].value, 'repeatedExtension'); + original.getExtension(FooExt.inners)[0].value, + 'repeatedExtension', + ); }); test('frozen message cannot be modified', () { - expect(() => original.inner = (Inner()..value = 'bar'), - throwsA(TypeMatcher())); - expect(() => original.inner..value = 'bar', - throwsA(TypeMatcher())); - expect(() => original.inners.add(Inner()..value = 'bar'), - throwsA(TypeMatcher())); + expect( + () => original.inner = (Inner()..value = 'bar'), + throwsA(TypeMatcher()), + ); + expect( + () => original.inner..value = 'bar', + throwsA(TypeMatcher()), + ); + expect( + () => original.inners.add(Inner()..value = 'bar'), + throwsA(TypeMatcher()), + ); }); test('extensions cannot be modified', () { - expect(() => original.setExtension(FooExt.inner, Inner()..value = 'bar'), - throwsA(TypeMatcher())); - expect(() => original.getExtension(FooExt.inner).value = 'bar', - throwsA(TypeMatcher())); expect( - () => - original.getExtension(FooExt.inners).add(Inner()..value = 'bar'), - throwsA(TypeMatcher())); + () => original.setExtension(FooExt.inner, Inner()..value = 'bar'), + throwsA(TypeMatcher()), + ); + expect( + () => original.getExtension(FooExt.inner).value = 'bar', + throwsA(TypeMatcher()), + ); + expect( + () => original.getExtension(FooExt.inners).add(Inner()..value = 'bar'), + throwsA(TypeMatcher()), + ); }); final builder = original.toBuilder() as Outer; @@ -50,8 +65,10 @@ void main() { expect(builder.inner, same(original.inner)); }); test('builder extensions are also copied shallowly', () { - expect(builder.getExtension(FooExt.inner), - same(original.getExtension(FooExt.inner))); + expect( + builder.getExtension(FooExt.inner), + same(original.getExtension(FooExt.inner)), + ); }); test('repeated fields are cloned', () { @@ -60,18 +77,25 @@ void main() { }); test('repeated extensions are cloned', () { - expect(builder.getExtension(FooExt.inners), - isNot(same(original.getExtension(FooExt.inners)))); - expect(builder.getExtension(FooExt.inners)[0], - same(original.getExtension(FooExt.inners)[0])); + expect( + builder.getExtension(FooExt.inners), + isNot(same(original.getExtension(FooExt.inners))), + ); + expect( + builder.getExtension(FooExt.inners)[0], + same(original.getExtension(FooExt.inners)[0]), + ); }); test( - 'the builder is only a shallow copy, the nested message is still frozen.', - () { - expect(() => builder.inner.value = 'bar', - throwsA(TypeMatcher())); - }); + 'the builder is only a shallow copy, the nested message is still frozen.', + () { + expect( + () => builder.inner.value = 'bar', + throwsA(TypeMatcher()), + ); + }, + ); test('the builder is mutable', () { builder.inner = (Inner()..value = 'zop'); expect(builder.inner.value, 'zop'); @@ -92,9 +116,10 @@ void main() { late OuterWithMap original; late OuterWithMap outerBuilder; setUp(() { - original = OuterWithMap() - ..innerMap[1] = (Inner()..value = 'mapInner') - ..freeze(); + original = + OuterWithMap() + ..innerMap[1] = (Inner()..value = 'mapInner') + ..freeze(); outerBuilder = original.toBuilder() as OuterWithMap; }); test('map fields are cloned', () { @@ -138,8 +163,10 @@ void main() { emptyMessage.freeze(); final builder = emptyMessage.toBuilder() as TestEmptyMessage; - builder.unknownFields - .addField(2, UnknownFieldSetField()..fixed32s.add(42)); + builder.unknownFields.addField( + 2, + UnknownFieldSetField()..fixed32s.add(42), + ); expect(builder.unknownFields.getField(2)!.fixed32s[0], 42); }); @@ -148,60 +175,93 @@ void main() { final builder = emptyMessage.toBuilder() as TestEmptyMessage; expect( - () => builder.unknownFields.getField(1)!.lengthDelimited[0] = - utf8.encode('alice'), - throwsA(TypeMatcher())); + () => + builder.unknownFields.getField(1)!.lengthDelimited[0] = utf8.encode( + 'alice', + ), + throwsA(TypeMatcher()), + ); }); test('cannot add to a frozen UnknownFieldSetField', () { emptyMessage.freeze(); expect( - () => field.addFixed32(1), throwsA(TypeMatcher())); - expect(() => field.fixed32s.add(1), - throwsA(TypeMatcher())); - expect(() => field.addFixed64(Int64(1)), - throwsA(TypeMatcher())); - expect(() => field.fixed64s.add(Int64(1)), - throwsA(TypeMatcher())); - expect(() => field.addLengthDelimited([1]), - throwsA(TypeMatcher())); - expect(() => field.lengthDelimited.add([1]), - throwsA(TypeMatcher())); - expect(() => field.addGroup(unknownFieldSet.clone()), - throwsA(TypeMatcher())); - expect(() => field.groups.add(unknownFieldSet.clone()), - throwsA(TypeMatcher())); - expect(() => field.addVarint(Int64(1)), - throwsA(TypeMatcher())); - expect(() => field.varints.add(Int64(1)), - throwsA(TypeMatcher())); + () => field.addFixed32(1), + throwsA(TypeMatcher()), + ); + expect( + () => field.fixed32s.add(1), + throwsA(TypeMatcher()), + ); + expect( + () => field.addFixed64(Int64(1)), + throwsA(TypeMatcher()), + ); + expect( + () => field.fixed64s.add(Int64(1)), + throwsA(TypeMatcher()), + ); + expect( + () => field.addLengthDelimited([1]), + throwsA(TypeMatcher()), + ); + expect( + () => field.lengthDelimited.add([1]), + throwsA(TypeMatcher()), + ); + expect( + () => field.addGroup(unknownFieldSet.clone()), + throwsA(TypeMatcher()), + ); + expect( + () => field.groups.add(unknownFieldSet.clone()), + throwsA(TypeMatcher()), + ); + expect( + () => field.addVarint(Int64(1)), + throwsA(TypeMatcher()), + ); + expect( + () => field.varints.add(Int64(1)), + throwsA(TypeMatcher()), + ); }); test('cannot add or merge field to a frozen UnknownFieldSet', () { emptyMessage.freeze(); - expect(() => unknownFieldSet.addField(2, field), - throwsA(TypeMatcher())); - expect(() => unknownFieldSet.mergeField(2, field), - throwsA(TypeMatcher())); + expect( + () => unknownFieldSet.addField(2, field), + throwsA(TypeMatcher()), + ); + expect( + () => unknownFieldSet.mergeField(2, field), + throwsA(TypeMatcher()), + ); }); test('cannot merge message into a frozen UnknownFieldSet', () { emptyMessage.freeze(); final other = emptyMessage.deepCopy(); - expect(() => emptyMessage.mergeFromBuffer(other.writeToBuffer()), - throwsA(TypeMatcher())); - expect(() => emptyMessage.mergeFromMessage(other), - throwsA(TypeMatcher())); + expect( + () => emptyMessage.mergeFromBuffer(other.writeToBuffer()), + throwsA(TypeMatcher()), + ); + expect( + () => emptyMessage.mergeFromMessage(other), + throwsA(TypeMatcher()), + ); }); test('cannot add a field to a frozen UnknownFieldSet', () { emptyMessage.freeze(); - expect(() => unknownFieldSet.addField(tagNumber, field), - throwsA(TypeMatcher())); + expect( + () => unknownFieldSet.addField(tagNumber, field), + throwsA(TypeMatcher()), + ); }); }); } diff --git a/protoc_plugin/test/unknown_field_set_test.dart b/protoc_plugin/test/unknown_field_set_test.dart index 0b35a65da..ab807c0fe 100644 --- a/protoc_plugin/test/unknown_field_set_test.dart +++ b/protoc_plugin/test/unknown_field_set_test.dart @@ -33,9 +33,13 @@ void main() { expect(s1 == s2, isFalse); expect(s2 == s1, isFalse); - expect(s1.hashCode == s2.hashCode, isFalse, - reason: '${s1.toString()} should have a different hash code ' - 'from ${s2.toString()}'); + expect( + s1.hashCode == s2.hashCode, + isFalse, + reason: + '${s1.toString()} should have a different hash code ' + 'from ${s2.toString()}', + ); } // Asserts that the given field sets are equal and have identical hash codes. @@ -76,8 +80,10 @@ void main() { expect(optionalGroupField.groups.length, 1); final group = optionalGroupField.groups[0]; expect(group.hasField(tagNumberA), isTrue); - expect(group.getField(tagNumberA)!.varints[0], - expect64(testAllTypes.optionalGroup.a)); + expect( + group.getField(tagNumberA)!.varints[0], + expect64(testAllTypes.optionalGroup.a), + ); }); test('testSerialize', () { @@ -92,27 +98,31 @@ void main() { test('testMergeFrom', () { // Source. - final sourceFieldSet = UnknownFieldSet() - ..addField(2, UnknownFieldSetField()..addVarint(make64(2))) - ..addField(3, UnknownFieldSetField()..addVarint(make64(3))); + final sourceFieldSet = + UnknownFieldSet() + ..addField(2, UnknownFieldSetField()..addVarint(make64(2))) + ..addField(3, UnknownFieldSetField()..addVarint(make64(3))); final source = TestEmptyMessage()..mergeUnknownFields(sourceFieldSet); // Destination. - final destinationFieldSet = UnknownFieldSet() - ..addField(1, UnknownFieldSetField()..addVarint(make64(1))) - ..addField(3, UnknownFieldSetField()..addVarint(make64(4))); + final destinationFieldSet = + UnknownFieldSet() + ..addField(1, UnknownFieldSetField()..addVarint(make64(1))) + ..addField(3, UnknownFieldSetField()..addVarint(make64(4))); - final destination = TestEmptyMessage() - ..mergeUnknownFields(destinationFieldSet) - ..mergeFromMessage(source); + final destination = + TestEmptyMessage() + ..mergeUnknownFields(destinationFieldSet) + ..mergeFromMessage(source); expect( - destination.toString(), - '1: 1\n' - '2: 2\n' - '3: 4\n' - '3: 3\n'); + destination.toString(), + '1: 1\n' + '2: 2\n' + '3: 4\n' + '3: 3\n', + ); }); test('testClear', () { @@ -132,8 +142,9 @@ void main() { test('testParseKnownAndUnknown', () { // Test mixing known and unknown fields when parsing. - final fields = unknownFields.clone() - ..addField(123456, UnknownFieldSetField()..addVarint(make64(654321))); + final fields = + unknownFields.clone() + ..addField(123456, UnknownFieldSetField()..addVarint(make64(654321))); final writer = CodedBufferWriter(); fields.writeToCodedBufferWriter(writer); @@ -211,27 +222,32 @@ void main() { expect(singularFieldNum, isNotNull); expect(repeatedFieldNum, isNotNull); - final fieldSet = UnknownFieldSet() - ..addField( - singularFieldNum, - UnknownFieldSetField() - ..addVarint(make64(TestAllTypes_NestedEnum.BAR.value)) - ..addVarint(make64(5))) - ..addField( - repeatedFieldNum, - UnknownFieldSetField() - ..addVarint(make64(TestAllTypes_NestedEnum.FOO.value)) - ..addVarint(make64(4)) - ..addVarint(make64(TestAllTypes_NestedEnum.BAZ.value)) - ..addVarint(make64(6))); + final fieldSet = + UnknownFieldSet() + ..addField( + singularFieldNum, + UnknownFieldSetField() + ..addVarint(make64(TestAllTypes_NestedEnum.BAR.value)) + ..addVarint(make64(5)), + ) + ..addField( + repeatedFieldNum, + UnknownFieldSetField() + ..addVarint(make64(TestAllTypes_NestedEnum.FOO.value)) + ..addVarint(make64(4)) + ..addVarint(make64(TestAllTypes_NestedEnum.BAZ.value)) + ..addVarint(make64(6)), + ); final writer = CodedBufferWriter(); fieldSet.writeToCodedBufferWriter(writer); { final message = TestAllTypes.fromBuffer(writer.toBuffer()); expect(message.optionalNestedEnum, TestAllTypes_NestedEnum.BAR); - expect(message.repeatedNestedEnum, - [TestAllTypes_NestedEnum.FOO, TestAllTypes_NestedEnum.BAZ]); + expect(message.repeatedNestedEnum, [ + TestAllTypes_NestedEnum.FOO, + TestAllTypes_NestedEnum.BAZ, + ]); final singularVarints = message.unknownFields.getField(singularFieldNum)!.varints; expect(singularVarints.length, 1); @@ -244,12 +260,18 @@ void main() { } { final message = TestAllExtensions.fromBuffer( - writer.toBuffer(), getExtensionRegistry()); - expect(message.getExtension(Unittest.optionalNestedEnumExtension), - TestAllTypes_NestedEnum.BAR); - - expect(message.getExtension(Unittest.repeatedNestedEnumExtension), - [TestAllTypes_NestedEnum.FOO, TestAllTypes_NestedEnum.BAZ]); + writer.toBuffer(), + getExtensionRegistry(), + ); + expect( + message.getExtension(Unittest.optionalNestedEnumExtension), + TestAllTypes_NestedEnum.BAR, + ); + + expect(message.getExtension(Unittest.repeatedNestedEnumExtension), [ + TestAllTypes_NestedEnum.FOO, + TestAllTypes_NestedEnum.BAZ, + ]); final singularVarints = message.unknownFields.getField(singularFieldNum)!.varints; expect(singularVarints.length, 1); @@ -263,34 +285,41 @@ void main() { }); test('testLargeVarint', () { - final unknownFieldSet = UnknownFieldSet() - ..addField( - 1, UnknownFieldSetField()..addVarint(make64(0x7FFFFFFF, 0xFFFFFFFF))); + final unknownFieldSet = + UnknownFieldSet()..addField( + 1, + UnknownFieldSetField()..addVarint(make64(0x7FFFFFFF, 0xFFFFFFFF)), + ); final writer = CodedBufferWriter(); unknownFieldSet.writeToCodedBufferWriter(writer); - final parsed = UnknownFieldSet() - ..mergeFromCodedBufferReader(CodedBufferReader(writer.toBuffer())); + final parsed = + UnknownFieldSet() + ..mergeFromCodedBufferReader(CodedBufferReader(writer.toBuffer())); final field = parsed.getField(1)!; expect(field.varints.length, 1); expect(field.varints[0], expect64(0x7FFFFFFF, 0xFFFFFFFFF)); }); test('testEquals', () { - final a = UnknownFieldSet() - ..addField(1, UnknownFieldSetField()..addFixed32(1)); + final a = + UnknownFieldSet()..addField(1, UnknownFieldSetField()..addFixed32(1)); - final b = UnknownFieldSet() - ..addField(1, UnknownFieldSetField()..addFixed64(make64(1))); + final b = + UnknownFieldSet() + ..addField(1, UnknownFieldSetField()..addFixed64(make64(1))); - final c = UnknownFieldSet() - ..addField(1, UnknownFieldSetField()..addVarint(make64(1))); + final c = + UnknownFieldSet() + ..addField(1, UnknownFieldSetField()..addVarint(make64(1))); - final d = UnknownFieldSet() - ..addField(1, UnknownFieldSetField()..addLengthDelimited([])); + final d = + UnknownFieldSet() + ..addField(1, UnknownFieldSetField()..addLengthDelimited([])); - final e = UnknownFieldSet() - ..addField(1, UnknownFieldSetField()..addGroup(unknownFields)); + final e = + UnknownFieldSet() + ..addField(1, UnknownFieldSetField()..addGroup(unknownFields)); checkEqualsIsConsistent(a); checkEqualsIsConsistent(b); @@ -309,10 +338,12 @@ void main() { checkNotEqual(c, e); checkNotEqual(d, e); - final f1 = UnknownFieldSet() - ..addField(1, UnknownFieldSetField()..addLengthDelimited([1, 2])); - final f2 = UnknownFieldSet() - ..addField(1, UnknownFieldSetField()..addLengthDelimited([2, 1])); + final f1 = + UnknownFieldSet() + ..addField(1, UnknownFieldSetField()..addLengthDelimited([1, 2])); + final f2 = + UnknownFieldSet() + ..addField(1, UnknownFieldSetField()..addLengthDelimited([2, 1])); checkEqualsIsConsistent(f1); checkEqualsIsConsistent(f2); @@ -321,13 +352,14 @@ void main() { }); test( - 'consistent hashcode for messages with no unknown fields set and an empty unknown field set', - () { - final m = TestAllExtensions(); - // Force an unknown field set. - final m2 = TestAllExtensions()..unknownFields; - expect(m.hashCode, m2.hashCode); - }); + 'consistent hashcode for messages with no unknown fields set and an empty unknown field set', + () { + final m = TestAllExtensions(); + // Force an unknown field set. + final m2 = TestAllExtensions()..unknownFields; + expect(m.hashCode, m2.hashCode); + }, + ); test('Copy length delimited fields', () { // Length-delimited fields should be copied before adding to the unknown @@ -336,11 +368,11 @@ void main() { final bytes = Uint8List.fromList([ 10, // tag = 1, type = length delimited originalBytes.length, - ...originalBytes + ...originalBytes, ]); - final parsed = UnknownFieldSet() - ..mergeFromCodedBufferReader(CodedBufferReader(bytes)); + final parsed = + UnknownFieldSet()..mergeFromCodedBufferReader(CodedBufferReader(bytes)); expect(parsed.getField(1)?.lengthDelimited, [originalBytes]); diff --git a/protoc_plugin/test/wire_format_test.dart b/protoc_plugin/test/wire_format_test.dart index 2cef92e97..182d8308d 100644 --- a/protoc_plugin/test/wire_format_test.dart +++ b/protoc_plugin/test/wire_format_test.dart @@ -15,17 +15,21 @@ void main() { test('testSerializationPacked', () { assertPackedFieldsSet( - TestPackedTypes.fromBuffer(getPackedSet().writeToBuffer())); + TestPackedTypes.fromBuffer(getPackedSet().writeToBuffer()), + ); }); test('testSerializeExtensions', () { assertAllFieldsSet( - TestAllTypes.fromBuffer(getAllExtensionsSet().writeToBuffer())); + TestAllTypes.fromBuffer(getAllExtensionsSet().writeToBuffer()), + ); }); test('testSerializePackedExtensions', () { - expect(getPackedExtensionsSet().writeToBuffer(), - getPackedSet().writeToBuffer()); + expect( + getPackedExtensionsSet().writeToBuffer(), + getPackedSet().writeToBuffer(), + ); }); test('testParseExtensions', () { @@ -44,7 +48,8 @@ void main() { final registry = getExtensionRegistry(); assertPackedExtensionsSet( - TestPackedExtensions.fromBuffer(rawBytes, registry)); + TestPackedExtensions.fromBuffer(rawBytes, registry), + ); }); test('testExtensionsSerialized', () { @@ -54,19 +59,23 @@ void main() { test('testParseMultipleExtensionRanges', () { // Make sure we can parse a message that contains multiple extensions // ranges. - final source = TestFieldOrderings() - ..myInt = make64(1) - ..myString = 'foo' - ..myFloat = 1.0 - ..setExtension(Unittest.myExtensionInt, 23) - ..setExtension(Unittest.myExtensionString, 'bar'); + final source = + TestFieldOrderings() + ..myInt = make64(1) + ..myString = 'foo' + ..myFloat = 1.0 + ..setExtension(Unittest.myExtensionInt, 23) + ..setExtension(Unittest.myExtensionString, 'bar'); - final registry = ExtensionRegistry() - ..add(Unittest.myExtensionInt) - ..add(Unittest.myExtensionString); + final registry = + ExtensionRegistry() + ..add(Unittest.myExtensionInt) + ..add(Unittest.myExtensionString); - final dest = - TestFieldOrderings.fromBuffer(source.writeToBuffer(), registry); + final dest = TestFieldOrderings.fromBuffer( + source.writeToBuffer(), + registry, + ); expect(dest, source); }); diff --git a/pubspec.yaml b/pubspec.yaml index 7896dba17..1404766b5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: workspace publish_to: none environment: - sdk: ^3.6.0 + sdk: ^3.7.0 workspace: - benchmarks