`pub add` create top-level attribute in block-style if possible. (#3423)
diff --git a/lib/src/command/add.dart b/lib/src/command/add.dart
index 0556434..196a7d6 100644
--- a/lib/src/command/add.dart
+++ b/lib/src/command/add.dart
@@ -405,17 +405,23 @@
'version': versionConstraintString
};
}
- final packagePath = [dependencyKey, name];
if (yamlEditor.parseAt(
[dependencyKey],
orElse: () => YamlScalar.wrap(null),
).value ==
null) {
- // Insert dependencyKey: {} if it did not exist.
- yamlEditor.update([dependencyKey], {});
+ // Handle the case where [dependencyKey] does not already exist.
+ // We ensure it is in Block-style by default.
+ yamlEditor.update(
+ [dependencyKey],
+ wrapAsYamlNode({name: pubspecInformation},
+ collectionStyle: CollectionStyle.BLOCK));
+ } else {
+ final packagePath = [dependencyKey, name];
+
+ yamlEditor.update(packagePath, pubspecInformation);
}
- yamlEditor.update(packagePath, pubspecInformation);
/// Remove the package from dev_dependencies if we are adding it to
/// dependencies. Refer to [_addPackageToPubspec] for additional discussion.
diff --git a/test/add/common/add_test.dart b/test/add/common/add_test.dart
index 82e098b..02459cc 100644
--- a/test/add/common/add_test.dart
+++ b/test/add/common/add_test.dart
@@ -7,6 +7,7 @@
import 'package:path/path.dart' as p;
import 'package:pub/src/exit_codes.dart' as exit_codes;
import 'package:test/test.dart';
+import 'package:yaml/yaml.dart';
import '../../descriptor.dart' as d;
import '../../test_pub.dart';
@@ -137,10 +138,47 @@
server.serve('foo', '1.2.3');
await d.dir(appPath, [
- d.pubspec({'name': 'myapp'})
+ d.file('pubspec.yaml', '''
+name: myapp
+environment:
+ "sdk": ">=0.1.2 <1.0.0"
+''')
]).create();
await pubAdd(args: ['foo:1.2.3']);
+ print(
+ File(p.join(d.sandbox, appPath, 'pubspec.yaml')).readAsStringSync());
+ final yaml = loadYaml(
+ File(p.join(d.sandbox, appPath, 'pubspec.yaml')).readAsStringSync());
+
+ expect(((yaml as YamlMap).nodes['dependencies'] as YamlMap).style,
+ CollectionStyle.BLOCK,
+ reason: 'Should create the mapping with block-style by default');
+ await d.cacheDir({'foo': '1.2.3'}).validate();
+ await d.appPackageConfigFile([
+ d.packageConfigEntry(name: 'foo', version: '1.2.3'),
+ ]).validate();
+ await d.appDir({'foo': '1.2.3'}).validate();
+ });
+
+ test('Inserts correctly when the pubspec is flow-style at top-level',
+ () async {
+ final server = await servePackages();
+ server.serve('foo', '1.2.3');
+
+ await d.dir(appPath, [
+ d.file('pubspec.yaml',
+ '{"name":"myapp", "environment": {"sdk": ">=0.1.2 <1.0.0"}}')
+ ]).create();
+
+ await pubAdd(args: ['foo:1.2.3']);
+
+ final yaml = loadYaml(
+ File(p.join(d.sandbox, appPath, 'pubspec.yaml')).readAsStringSync());
+
+ expect(((yaml as YamlMap).nodes['dependencies'] as YamlMap).style,
+ CollectionStyle.FLOW,
+ reason: 'Should not break a pubspec in flow-style');
await d.cacheDir({'foo': '1.2.3'}).validate();
await d.appPackageConfigFile([