remove method
Removes the node at path
. Comments "belonging" to the node will be
removed while surrounding comments will be left untouched.
Throws an ArgumentError if path
is invalid.
Throws an AliasException if a node on path
is an alias or anchor.
Example:
final doc = YamlEditor('''
- 0 # comment 0
# comment A
- 1 # comment 1
# comment B
- 2 # comment 2
''');
doc.remove([1]);
Expected Result:
'''
- 0 # comment 0
# comment A
# comment B
- 2 # comment 2
'''
Implementation
YamlNode remove(Iterable<Object?> path) {
late SourceEdit edit;
late YamlNode expectedNode;
final nodeToRemove = _traverse(path, checkAlias: true);
if (path.isEmpty) {
edit = SourceEdit(0, _yaml.length, '');
expectedNode = wrapAsYamlNode(null);
/// Parsing an empty YAML document returns YamlScalar with value `null`.
_performEdit(edit, path, expectedNode);
return nodeToRemove;
}
final pathAsList = path.toList();
final collectionPath = pathAsList.take(path.length - 1);
final keyOrIndex = pathAsList.last;
final parentNode = _traverse(collectionPath);
if (parentNode is YamlList) {
edit = removeInList(this, parentNode, keyOrIndex as int);
expectedNode = wrapAsYamlNode(
[...parentNode.nodes]..removeAt(keyOrIndex),
);
} else if (parentNode is YamlMap) {
edit = removeInMap(this, parentNode, keyOrIndex);
expectedNode =
updatedYamlMap(parentNode, (nodes) => nodes.remove(keyOrIndex));
}
_performEdit(edit, collectionPath, expectedNode);
return nodeToRemove;
}