[analysis_server] Add a missing "break" to ChangeBuilder that could result in duplicate imports Changes that add combinators to an import would also insert a duplicate import if they were not the last import, due to a missing "break" as they looped over the existing imports. Change-Id: I3bf106a200be9ad102487f749df9fe4a9e89fb79 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/383260 Reviewed-by: Samuel Rawlins <srawlins@google.com> Commit-Queue: Brian Wilkerson <brianwilkerson@google.com> Reviewed-by: Brian Wilkerson <brianwilkerson@google.com>
diff --git a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart index 53c5c33..fed3d05 100644 --- a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart +++ b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart
@@ -1984,6 +1984,7 @@ if (isReplacement) { insert(replace: existingImport); + break; } else if (isDart) { if (!isExistingDart || isNewBeforeExisting) { insert(
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart index c2c666a..d82a3b5 100644 --- a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart +++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart
@@ -1831,6 +1831,37 @@ "import 'package:test/test_a.dart' show A, Other;A")); } + /// The same test as [test_writeType_shownImport] but where the updated + /// import is not the last import. This verifies the code that updates imports + /// correctly breaks after updating the import so it does not also import a + /// duplicate. + Future<void> test_writeType_shownImport_nonLast() async { + var aPath = convertPath('/home/test/lib/test_a.dart'); + var aContent = 'class A {} class Other {}'; + addSource(aPath, aContent); + var bPath = convertPath('/home/test/lib/test_b.dart'); + var bContent = ''' +import 'package:test/test_a.dart' show Other; +import 'package:test/test_b.dart'; +'''; + addSource(bPath, bContent); + + var builder = await newBuilder(); + var typeA = await _getType(aPath, 'A'); + await builder.addDartFileEdit(bPath, (builder) { + builder.addInsertion(bContent.length, (builder) { + builder.writeType(typeA); + }); + }); + var edits = getEdits(builder); + expect(edits, hasLength(2)); + var edited = SourceEdit.applySequence(bContent, edits); + expect(edited, equalsIgnoringWhitespace(''' +import 'package:test/test_a.dart' show A, Other; +import 'package:test/test_b.dart'; +A''')); + } + Future<void> test_writeType_shownImportUnsorted() async { var aPath = convertPath('/home/test/lib/test_a.dart'); var aContent = 'class A {} class B {} class C {} class D {}';