findOne method

Element findOne(
  1. Finder finder
)

Like find but asserts exactly one match and returns it. On zero or multiple matches, invokes the configured failure handler with a dump of the current tree.

Implementation

Element findOne(Finder finder) {
  final matches = find(finder);
  if (matches.length == 1) return matches.single;
  final msg = StringBuffer()
    ..write('Expected exactly one element matching ${finder.describe()}, ')
    ..writeln('found ${matches.length}.');
  if (matches.isNotEmpty) {
    msg.writeln('Matches:');
    for (final m in matches) {
      msg.write('  ');
      msg.writeln(m.toStringShallow());
    }
  }
  msg
    ..writeln('Current tree:')
    ..write(_root?.toStringDeep('  ') ?? '  (no root)');
  _failureHandler(msg.toString());
}