Fix __delitem__ in prettytoml's table element

Two bugs involved here.

First of all, __delitem__ uses _find_following_newline to find where the
line to delete ends, which in turns looks for the next closest newline
element. But if the previous line ends with a comment element (which
implies a newline), it will also be deleted. This would be a problem if
the comment is inline.

foo=1  # comment
bar=2

In this minimal example, the elements in play are

AtomicElement('foo')
PunctuationElement('=')
AtomicElement(1)
WhitespaceElement('  ')
CommentElement('# comment')
AtomicElement('bar')
PunctuationElement('=')
AtomicElement(2)

When deleting "foo", it starts from AtomicElement('foo') and looks for
the next newline, but does not consider CommentElement, ending up
deleting all elements. This fix replaces _find_following_newline with
_find_following_line_terminator, which does consider both newline and
comment elements.

Also there is a logic error in _find_following_line_terminator that
prevents it from even working. The two -inf/inf clauses should serve as
guards when either or both indexes are infinity, but they were
flip-flopped and not working at all. This change doesn't seem to affect
existing tests (at least not breaking them more than they already were).

Fix #1535.
This commit is contained in:
Tzu-ping Chung
2018-03-03 23:48:27 +08:00
parent 6bb67a8ab0
commit b411d20bd1
2 changed files with 3 additions and 3 deletions
+1 -1
View File
@@ -105,7 +105,7 @@ class TableElement(abstracttable.AbstractTable):
preceding_newline = self._find_preceding_newline(begin)
if preceding_newline >= 0:
begin = preceding_newline
end = self._find_following_newline(begin)
end = self._find_following_line_terminator(begin)
if end < 0:
end = len(tuple(self._sub_elements))
self._sub_elements = self.sub_elements[:begin] + self.sub_elements[end:]
@@ -76,9 +76,9 @@ class TraversalMixin:
following_comment = self._find_following_comment(index)
following_newline = self._find_following_newline(index)
if following_comment == float('-inf'):
if following_comment == float('inf'):
return following_newline
if following_newline == float('inf'):
if following_newline == float('-inf'):
return following_comment
if following_newline < following_comment: