Skip to content

Commit 38f1549

Browse files
authored
update the generator to emit formatted files (#1020)
1 parent 04bd6ac commit 38f1549

25 files changed

+249
-233
lines changed

.github/workflows/dart.yml

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ jobs:
8080
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684
8181
with:
8282
path: "~/.pub-cache/hosted"
83-
key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:benchmarks;commands:format-command_0-command_1-analyze_0"
83+
key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:benchmarks;commands:format_0-command_0-command_1-analyze_0"
8484
restore-keys: |
8585
os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:benchmarks
8686
os:ubuntu-latest;pub-cache-hosted;sdk:dev
@@ -122,7 +122,7 @@ jobs:
122122
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684
123123
with:
124124
path: "~/.pub-cache/hosted"
125-
key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:protobuf;commands:format-analyze_0"
125+
key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:protobuf;commands:format_0-analyze_0"
126126
restore-keys: |
127127
os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:protobuf
128128
os:ubuntu-latest;pub-cache-hosted;sdk:dev
@@ -149,14 +149,14 @@ jobs:
149149
if: "always() && steps.protobuf_pub_upgrade.conclusion == 'success'"
150150
working-directory: protobuf
151151
job_005:
152-
name: "format_analyze; linux; Dart dev; PKG: protoc_plugin; `dart format --output=none --set-exit-if-changed .`, `./../tool/setup.sh`, `make protos`, `dart analyze --fatal-infos`"
152+
name: "format_analyze; linux; Dart dev; PKG: protoc_plugin; `dart format --output=none --set-exit-if-changed lib`, `./../tool/setup.sh`, `make protos`, `dart analyze --fatal-infos`"
153153
runs-on: ubuntu-latest
154154
steps:
155155
- name: Cache Pub hosted dependencies
156156
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684
157157
with:
158158
path: "~/.pub-cache/hosted"
159-
key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:protoc_plugin;commands:format-command_0-command_2-analyze_0"
159+
key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:protoc_plugin;commands:format_1-command_0-command_2-analyze_0"
160160
restore-keys: |
161161
os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:protoc_plugin
162162
os:ubuntu-latest;pub-cache-hosted;sdk:dev
@@ -174,8 +174,8 @@ jobs:
174174
run: dart pub upgrade
175175
if: "always() && steps.checkout.conclusion == 'success'"
176176
working-directory: protoc_plugin
177-
- name: "protoc_plugin; dart format --output=none --set-exit-if-changed ."
178-
run: "dart format --output=none --set-exit-if-changed ."
177+
- name: "protoc_plugin; dart format --output=none --set-exit-if-changed lib"
178+
run: "dart format --output=none --set-exit-if-changed lib"
179179
if: "always() && steps.protoc_plugin_pub_upgrade.conclusion == 'success'"
180180
working-directory: protoc_plugin
181181
- name: protoc_plugin; ./../tool/setup.sh

protoc_plugin/CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
## 22.4.1-wip
1+
## 22.5.0-wip
22

3+
* Generated files are now formatted using the Dart formatter. The code is
4+
formatted using the min. SDK for `package:protoc_plugin`; currently `3.7.0`.
35
* Minimum SDK dependency bumped from 3.6.0 to 3.7.0. ([#1024])
46

57
[#1024]: https://github.com/google/protobuf.dart/pull/1024

protoc_plugin/Makefile

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,14 +89,11 @@ $(TEST_PROTO_LIBS): $(PLUGIN_SRC) $(TEST_PROTO_SRCS)
8989
--plugin=protoc-gen-dart=$(realpath $(PLUGIN_PATH))\
9090
$(TEST_PROTO_SRCS)
9191

92-
dart format $(TEST_PROTO_DIR)
93-
9492
update-pregenerated: $(PLUGIN_PATH) $(PREGENERATED_SRCS)
9593
protoc --dart_out=lib/src/gen \
9694
-Iprotos \
9795
--plugin=protoc-gen-dart=$(realpath $(PLUGIN_PATH)) $(PREGENERATED_SRCS)
9896
find lib/src/gen -name '*.pbjson.dart' -delete
99-
dart format lib/src/gen
10097

10198
protos: $(PLUGIN_PATH) $(TEST_PROTO_LIBS)
10299

protoc_plugin/lib/indenting_writer.dart

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import 'dart:collection';
66

7+
import 'src/formatter.dart' as formatter;
78
import 'src/gen/google/protobuf/descriptor.pb.dart';
89

910
/// Specifies code locations where metadata annotations should be attached and
@@ -22,6 +23,9 @@ class NamedLocation {
2223

2324
/// A buffer for writing indented source code.
2425
class IndentingWriter {
26+
final String? fileName;
27+
final bool generateMetadata;
28+
2529
final StringBuffer _buffer = StringBuffer();
2630
final GeneratedCodeInfo sourceLocationInfo = GeneratedCodeInfo();
2731

@@ -30,12 +34,11 @@ class IndentingWriter {
3034
// After writing any chunk, _previousOffset is the size of everything that was
3135
// written to the buffer before the latest call to print or addBlock.
3236
int _previousOffset = 0;
33-
final String? _sourceFile;
3437

3538
// Named text sections to write at the end of the file.
3639
final Map<String, String> _suffixes = SplayTreeMap();
3740

38-
IndentingWriter({String? filename}) : _sourceFile = filename;
41+
IndentingWriter({this.fileName, this.generateMetadata = false});
3942

4043
/// Appends a string indented to the current level.
4144
/// (Indentation will be added after newline characters where needed.)
@@ -138,18 +141,27 @@ class IndentingWriter {
138141
_suffixes[suffixKey] = text;
139142
}
140143

141-
@override
142-
String toString() {
144+
/// Emit the generated source.
145+
///
146+
/// This is safe to call multiple times.
147+
String emitSource({required bool format}) {
143148
if (_suffixes.isNotEmpty) {
144-
// TODO: We may want to introduce the notion of closing the writer.
145149
println('');
146150
for (final key in _suffixes.keys) {
147151
println(_suffixes[key]!);
148152
}
149153
_suffixes.clear();
150154
}
151155

152-
return _buffer.toString();
156+
var source = _buffer.toString();
157+
158+
// We don't always want to format the source (for example, we don't want to
159+
// format if we're creating annotated locations of source elements).
160+
if (format) {
161+
source = formatter.format(source);
162+
}
163+
164+
return source;
153165
}
154166

155167
/// Writes part of a line of text.
@@ -175,16 +187,15 @@ class IndentingWriter {
175187
/// string that was passed to the previous [print]. Name should be the string
176188
/// that was written to file.
177189
void _addAnnotation(List<int> fieldPath, String name, int start) {
178-
if (_sourceFile == null) {
179-
return;
190+
if (generateMetadata) {
191+
final annotation =
192+
GeneratedCodeInfo_Annotation()
193+
..path.addAll(fieldPath)
194+
..sourceFile = fileName!
195+
..begin = _previousOffset + start
196+
..end = _previousOffset + start + name.length;
197+
sourceLocationInfo.annotation.add(annotation);
180198
}
181-
final annotation =
182-
GeneratedCodeInfo_Annotation()
183-
..path.addAll(fieldPath)
184-
..sourceFile = _sourceFile
185-
..begin = _previousOffset + start
186-
..end = _previousOffset + start + name.length;
187-
sourceLocationInfo.annotation.add(annotation);
188199
}
189200
}
190201

protoc_plugin/lib/src/file_generator.dart

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -263,14 +263,19 @@ class FileGenerator extends ProtobufContainer {
263263
final mainWriter = generateMainFile(config);
264264
final enumWriter = generateEnumFile(config);
265265

266+
final generateMetadata = options.generateMetadata;
267+
266268
final files = [
267-
makeFile('.pb.dart', mainWriter.toString()),
268-
makeFile('.pbenum.dart', enumWriter.toString()),
269+
makeFile('.pb.dart', mainWriter.emitSource(format: !generateMetadata)),
270+
makeFile(
271+
'.pbenum.dart',
272+
enumWriter.emitSource(format: !generateMetadata),
273+
),
269274
// TODO(devoncarew): Consider not emitting empty json files.
270275
makeFile('.pbjson.dart', generateJsonFile(config)),
271276
];
272277

273-
if (options.generateMetadata) {
278+
if (generateMetadata) {
274279
files.addAll([
275280
makeFile(
276281
'.pb.dart.meta',
@@ -291,13 +296,17 @@ class FileGenerator extends ProtobufContainer {
291296
files.add(makeFile('.pbserver.dart', generateServerFile(config)));
292297
}
293298
}
299+
294300
return files;
295301
}
296302

297303
/// Creates an IndentingWriter with metadata generation enabled or disabled.
298-
IndentingWriter makeWriter() => IndentingWriter(
299-
filename: options.generateMetadata ? descriptor.name : null,
300-
);
304+
IndentingWriter makeWriter() {
305+
return IndentingWriter(
306+
fileName: descriptor.name,
307+
generateMetadata: options.generateMetadata,
308+
);
309+
}
301310

302311
/// Returns the contents of the .pb.dart file for this .proto file.
303312
IndentingWriter generateMainFile([
@@ -569,7 +578,7 @@ class FileGenerator extends ProtobufContainer {
569578
s.generate(out);
570579
}
571580

572-
return out.toString();
581+
return out.emitSource(format: true);
573582
}
574583

575584
/// Returns the contents of the .pbgrpc.dart file for this .proto file.
@@ -606,7 +615,7 @@ class FileGenerator extends ProtobufContainer {
606615
generator.generate(out);
607616
}
608617

609-
return out.toString();
618+
return out.emitSource(format: true);
610619
}
611620

612621
void writeBinaryDescriptor(
@@ -699,7 +708,7 @@ class FileGenerator extends ProtobufContainer {
699708
out.println('');
700709
}
701710

702-
return out.toString();
711+
return out.emitSource(format: true);
703712
}
704713

705714
/// Returns the generator for each .pbjson.dart file the generated

protoc_plugin/lib/src/formatter.dart

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
import 'package:dart_style/dart_style.dart';
6+
import 'package:pub_semver/pub_semver.dart';
7+
8+
// Note: keep this in sync with the SDK constraint in pubspec.yaml.
9+
final Version formatUsingVersion = Version(3, 6, 0);
10+
11+
final DartFormatter _formatter = DartFormatter(
12+
languageVersion: formatUsingVersion,
13+
);
14+
15+
/// Return the Dart formatted version of the given source.
16+
String format(String source) => _formatter.format(source);

protoc_plugin/mono_pkg.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
stages:
33
- format_analyze:
44
- group:
5-
- format
5+
- format: --output=none --set-exit-if-changed lib
66
- command: ./../tool/setup.sh
77
- command: make protos
88
- analyze: --fatal-infos

protoc_plugin/pubspec.yaml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,24 @@
11
name: protoc_plugin
2-
version: 22.4.1-wip
2+
version: 22.5.0-wip
33
description: A protobuf protoc compiler plugin used to generate Dart code.
44
repository: https://github.com/google/protobuf.dart/tree/master/protoc_plugin
55

66
environment:
7+
# Note: keep this in sync with the SDK version in lib/src/formatter.dart.
78
sdk: ^3.7.0
89

910
resolution: workspace
1011

1112
dependencies:
1213
collection: ^1.15.0
14+
dart_style: ^3.0.0
1315
fixnum: ^1.0.0
1416
path: ^1.8.0
1517
protobuf: ^4.1.0
18+
pub_semver: ^2.2.0
1619

1720
dev_dependencies:
18-
dart_style: ^3.1.0
1921
lints: '>=5.0.0 <7.0.0'
20-
pub_semver: ^2.2.0
2122
test: ^1.16.0
2223

2324
executables:

protoc_plugin/test/client_generator_test.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,6 @@ void main() {
3333

3434
final writer = IndentingWriter();
3535
cag.generate(writer);
36-
expectGolden(writer.toString(), 'client.pb.dart');
36+
expectGolden(writer.emitSource(format: true), 'client.pb.dart');
3737
});
3838
}

protoc_plugin/test/const_generator_test.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import 'package:test/test.dart';
99
String toConst(Object? val) {
1010
final out = IndentingWriter();
1111
writeJsonConst(out, val);
12-
return out.toString();
12+
return out.emitSource(format: false);
1313
}
1414

1515
void main() {

0 commit comments

Comments
 (0)