-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.py
More file actions
1948 lines (1679 loc) · 51.7 KB
/
tree.py
File metadata and controls
1948 lines (1679 loc) · 51.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""XML tree representation.
Node types are: `Tree`, `Tag`, `Comment`, `String`, `Instruction`. Attributes
are not represented as nodes, even though they are treated like that in the
xpath model, because this would be weird in python.
All node types derive from an abstract base class `Node`. `Tree` and `Tag` nodes
derive from an abstract class `Branch`, which itself derives from `Node`. There
is no inheritance relationship between concrete node types. For instance,
`Comment` is not a subclass of `String`, unlike in BeautifulSoup. Thus, to check
whether a node is of a concrete given type `T`, using `isinstance(node, T)`,
etc. is sufficient. And to check whether a node is a branch or a leaf, it is
sufficient to check `isinstance(node, Branch)`.
When parsing documents and when modifying attributes, we always normalize spaces
in attributes: we replace all sequences of whitespace characters with " " and we
trim whitespace from both sides. Thus, an attribute with only whitespace is
considered empty. Furthermore, we don't make a distinction between an empty or
blank attribute and an attribute that is not explicitly given. Thus, we assume
that `<foo bar="">` and `<foo bar=" ">` are identical to `<foo>`. This is
wrong, but it doesn't cause much harm in practice, and considerably simplifies
processing. It is still possible to check whether an attribute is explicitly
given by using the Node.keys() method.
For simplicity, we do not deal with XML namespaces at all. We just remove
namespace prefixes in both elements and attributes. Thus, `<xsl:template>`
becomes `<template>`, and `<foo xml:lang="eng">` becomes `<foo lang="eng">`.
This means that we cannot deal with documents where namespaces are significant.
This also means that we cannot properly serialize XML documents that used
namespaces initially. However, the resulting simplicity trumps this
not-so-accurate processing.
We use XPath expressions for searching and matching, but only support a small
subset of it. Most notably, it is only possible to select `Tag` and `Tree`
nodes. Other types of nodes, attributes in particular, can only be used in
predicates viz. within brackets, as in `foo[@bar]`. We also do not support
expressions that index node sets in some way (because we are using generators
instead of lists for computing intermediate results). Thus, testing a node
position in a node set or evaluating the length of a node set is not possible.
There is one notable difference with XPath: the text() function does not return
strings from the tree, but returns instead a (space-normalized) string which
concatenates all string nodes under a given subtree.
For convenience, we add a few extra axes to XPath's default. They are:
* `stuck-child`.
Returns the first child element of the current node, iff there is no
text or just whitespace between the current node and this child. This
only ever returns one child.
* `stuck-parent`.
Reverse of stuck-child.
* `stuck-following-sibling`.
Returns the first following sibling of the current node, iff there is no
text or just whitespace between the current node and this sibling. This
only ever returns one sibling.
* `stuck-preceding-sibling`.
Reverse of stuck-preceding-sibling.
XPath expressions can use the following functions:
`glob(pattern[, text])`, `iglob(pattern[, text])`
Checks if `text` matches the given glob `pattern`. If `text` is not given, it
defaults to the node's text contents. `iglob` is like `glob`, but is
case-insensitive. In addition, we have:
`regex(pattern[, text])`
Like `glob`, but for regular expressions. Matching is unanchored, so `^` and `$`
must be used if the idea is to match a full string.
`name()` `mixed()`, `empty()`, `plain()`, `text()`
Returns the corresponding attributes in `Node`.
To evaluate an expression, we first convert it to straightforward python source
code, then compile the result, and finally run the code. Compiled expressions
are saved in a global table and are systematically reused. There is no caching
policy for now, so it is not a good idea to generate expressions on-the-fly.
The xpath.py command-line tool can be used for evaluating xpath expressions. If
it is not given any file to search into, it just prints the Python code that
will be used for evaluating the given expression.
"""
# TODO add a "fallback" handler (or maybe a different parser) for processing
# stuff simple document that are not necessarily XML viz. documents with
# several root elements or without a root element.
import os, re, io, collections, sys, fnmatch, tokenize, traceback
from typing import *
from xml.parsers import expat
from xml.sax.saxutils import escape as quote_string
from pegen.tokenizer import Tokenizer
from typing import SupportsIndex
from dharma.xpath_parser import Path, Step, Op, Func, GeneratedParser
from dharma import texts
Location = collections.namedtuple("Location", "start end line column")
"""Represents the location of a node in an XML file. Fields are:
* `start`: byte index of the start of the node
* `end`: idem for the end of the node
* `line`: line number (one-based)
* `column`: column number (one-based)
"""
# We don't use xml.sax.saxutils.quoteattr because it tries to use ' for
# quoting attributes, and people generally use " instead. We want to preserve
# the original as much as possible.
attribute_tbl = str.maketrans({
'"': """,
"<": "<",
">": ">",
"&": "&",
})
def escape_attribute(s):
return s.translate(attribute_tbl)
def quote_attribute(s):
return f'"{escape_attribute(s)}"'
def _sorted(nodes):
"Sort nodes in document order. Returns a list."
nodes = list(nodes)
if not nodes:
return nodes
node_set = set(nodes)
t = nodes[0].tree
nodes.clear()
def inner(root):
if root in node_set:
nodes.append(root)
if isinstance(root, Branch):
for child in root:
inner(child)
inner(t)
assert len(nodes) == len(node_set)
return nodes
def parse_string(source, path=None):
"""Parse an XML string into a `Tree`. If `path` is given, it will be
used as filename in error messages, and will be accessible through
the `file` attribute."""
# We always pass byte strings to the parser because expat only
# reports byte offsets, not code points offsets, so, to report
# errors locations properly, we need a byte string.
if isinstance(source, str):
source = source.encode()
try:
return _Parser(source, path=path).parse()
except expat.ExpatError as e:
err = e
# https://docs.python.org/3/library/pyexpat.html#xml.parsers.expat.XMLParserType
# err.offset counts columns from 0
raise Error(path=path or "",
line=err.lineno, column=err.offset + 1,
text=expat.errors.messages[err.code], source=source)
def parse(file, path=None):
"""Parse an XML file into a `Tree`. The `file` argument can either be a
file-like object or a string that indicates the file's path. The `path`
argument can be used to indicate the file's path, for errors messages.
If it is not given, the path of the file will be deduced from `file`,
if possible."""
if isinstance(file, texts.File):
source = file.data
if not path:
path = file.full_path
elif hasattr(file, "read"):
# assume file-like
source = file.read()
if not path and file is not sys.stdin and hasattr(file, "name"):
path = os.path.abspath(str(file.name))
else:
with open(file, "rb") as f:
source = f.read()
if not path:
path = os.path.abspath(file)
return parse_string(source, path=path)
class Node:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.location: Location | None = None
"""`Location` object, which indicates the boundaries of the
subtree in the XML source it was constructed from. If the
subtree does not come from an XML file, `Location` is `None`.
Likewise, if the subtree is modified in some way, or if it is
extracted from the original tree or copied from it, `Location`
will be set to `None`."""
# Parent node.
self._parent = None
self.notes: dict = {}
"""A dictionary for storing arbitrary data."""
@property
def tree(self):
"""The `Tree` this node belongs to. If the node is a `Tree`,
this returns the `Tree` itself."""
node = self
while not isinstance(node, Tree):
node = node.parent
return node
@property
def file(self) -> str | None:
"Path of the XML file this subtree was constructed from."
return self.tree.file
@property
def parent(self) -> "Branch | None":
"""Parent node. All nodes have a parent, except `Tree` nodes,
whose parent is `None`."""
# Newly created nodes are not immediately attached to a tree.
# It is only if an attempt is made to access a node's tree
# that a new tree is allocated. We do this to avoid creating
# new tree objects for each new node, when in practice most
# nodes will be immediately appended to an existing tree.
ret = self._parent
if ret is None:
ret = Tree()
self._parent = ret
list.append(ret, self)
return ret
@property
def path(self) -> str:
"The path of this node. See the `locate` method."
raise NotImplementedError
def comment_out(self, **kwargs):
"""Comments out a node viz. replaces it with a commented out XML
representation of it. Keyword arguments are the same as the ones
of the `.xml()` method."""
tmp = self.xml(**kwargs)
self.replace_with(Comment(tmp))
return self
@property
def mixed(self) -> bool:
"""Whether this node has both `Tag` and non-blank `String`
children. This can only be called on `Branch` nodes."""
raise Exception("invalid operation")
@property
def empty(self) -> bool:
"""`True` if this node has no `Tag` children nor non-blank
`String` children. This can only be called on `Branch` nodes."""
raise Exception("invalid operation")
@property
def plain(self) -> bool:
"""`True` if this node is a `String`, or if it is a `Branch`
that has no children or only `String` children (discounting
comments and processing instructions)."""
return False
def __hash__(self):
return id(self)
def __bool__(self):
return True
@property
def source(self) -> str | None:
"""XML source of this subtree, as it appears in the file it
was parsed from, as a string. If the `location` member is
`None`, `source` will also be `None`.
"""
source = self.byte_source
if source:
return source.decode()
@property
def byte_source(self) -> bytes | None:
"XML source of this subtree, in bytes, encoded as UTF-8."
source = self.tree.byte_source
location = self.location
if source and location:
return source[location.start:location.end]
@property
def root(self) -> "Tag":
"""The root `Tag` node of the `Tree` this subtree belongs to.
Raises an error if the `Tree` does not have one or has many.
"""
return self.tree.root
def append(self, node: "Node | str"):
raise NotImplementedError
def prepend(self, node: "Node | str"):
raise NotImplementedError
def stuck_child(self):
"""Returns the first `Tag` child of this node, if it has one
and if there is no intervening non-blank text in-between. Can
only be called on `Branch` nodes.
"""
pass
def stuck_parent(self):
"Reverse of `stuck_child()`."
parent = self.parent
if parent and parent.stuck_child() is self:
return parent
def stuck_following_sibling(self):
"""Returns the first `Tag` sibling of this node, if it has one
and if there is no intervening non-blank text in-between. Can
only be called on `Tag` nodes.
"""
raise Exception("bad operation")
def stuck_preceding_sibling(self):
"""Reverse of stuck_preceding_sibling()."""
raise Exception("bad operation")
def strings(self) -> list["String"]:
return []
def delete(self):
"""Removes this node and all its descendants from the tree.
Returns the removed subtree."""
parent = self._parent
if parent:
parent.remove(self)
return self
self._parent = None
self.location = None
return self
_location_re = re.compile(r"/(\w+)\[([1-9][0-9]*)\]", re.ASCII)
def locate(self, path):
"""Finds the node that matches the given xpath expression.
This only works for basic expressions of the form:
`/`, `/foo[1]`, `/foo[1]/bar[5]`, etc. The path of a node
is given in its `path` attribute.
"""
orig = path
node = self.tree
if path == "/":
return node
while True:
match = self._location_re.match(path)
if not match:
raise Exception(f"invalid location {orig!r}")
name, index = match.group(1), int(match.group(2))
i = 0
for node in node:
if isinstance(node, Tag) and node.name == name:
i += 1
if i == index:
break
else:
raise Exception(f"node {orig!r} not found")
end = match.end()
if end == len(path):
break
path = path[end:]
return node
def find(self, path: str, sort: bool=False) -> list['Node']:
"""Finds nodes that match the given XPath expression.
Returns a list of matching nodes. If `sort` is True, nodes are
sorted in document order before being returned. Otherwise, they
might appear in any order.
"""
f = generator.compile(path)
if sort:
return _sorted(f(self))
return list(f(self))
def first(self, path: str, sort: bool=False) -> "Node | None":
"""Like the `find` method, but returns only the first matching
node, or `None` if there is no match."""
f = generator.compile(path)
if sort:
return next(_sorted(f(self)), None)
return next(f(self), None)
@staticmethod
def match_func(path: str):
"""Returns a function that matches the given path if called on
a `Node` object. See the documentation of `Node.matches()`."""
return generator.compile(path, search=False)
def matches(self, path: str) -> bool:
"""Checks if this node matches the given XPath expression.
Returns a boolean.
The expression is evaluated like an XSLT pattern. For details,
see the XSLT 1.0 standard, under § 5.2 Patterns.
"""
f = self.match_func(path)
return f(self)
def children(self) -> list['Node']:
"""Returns a list of `Tag` children of this node."""
return []
def replace_with(self, *replacement_nodes) -> 'Node':
"""Removes this node and its descendants from the tree, and
in its place the nodes given as arguments. Returns the removed
subtree.
"""
parent = self.parent
assert parent is not None
i = parent.index(self)
del parent[i]
for i, node in enumerate(replacement_nodes, i):
parent.insert(i, node)
return self
def insert_after(self, other):
"""Insert a node just after the current one.
This cannot be called on a `Tree`, obviously."""
parent = self.parent
assert parent is not None
i = parent.index(self)
parent.insert(i + 1, other)
def insert_before(self, other: "Node | str"):
"""Insert a node just before the current one.
This cannot be called on a `Tree`, obviously."""
parent = self.parent
assert parent is not None
i = parent.index(self)
parent.insert(i, other)
def text(self, space="default") -> str:
"""Returns the text contents of this subtree. Per default, we do
normalize-space(); to prevent this, pass `space="preserve"`.
"""
return ""
def xml(self, strip_comments=False, strip_instructions=False,
html=False, color=False, add_xml_prefix=True):
"""Returns an XML representation of this subtree.
If `html` is true, the result will be escaped, for inclusion
in an HTML file. If `color` is true, the result will be
colorized, either through CSS classes (if `html` is true),
or with ANSI escapes codes (otherwise).
"""
fmt = Formatter(strip_comments=strip_comments,
strip_instructions=strip_instructions, html=html,
color=color, add_xml_prefix=add_xml_prefix)
fmt.format(self)
return fmt.text()
def html(self):
fmt = Formatter(strip_comments=True, strip_instructions=True,
html=False, color=False, add_xml_prefix=False, self_closing=False)
fmt.format(self)
return fmt.text()
def __iter__(self):
raise NotImplementedError
def __copy__(self):
return self.copy()
def __deepcopy__(self, memo):
return self.copy()
def copy(self):
"""Makes a copy of this subtree. The returned object holds no
reference to the original. It is bound to a new `Tree`."""
raise NotImplementedError
def unwrap(self):
"""Removes a node from the tree but leaves its descendants
in-place. Returns the detached node.
This cannot be called on a `Tree` node. Also note that
unwrapping the root `Tag` node of a `Tree` might yield
an invalid XML document that contains several roots."""
self.delete()
return self
def coalesce(self):
"""Coalesces adjacent string nodes and removes empty string
nodes from this subtree. Has no effect on leaf nodes. In
particular, if this is called on an empty `String` node, this
node will not be removed from the tree."""
pass
class Branch(Node, list):
"""Base class for non-leaf nodes viz. `Tree` nodes and `Tag` nodes.
Branches are represented as lists of nodes. They support most `list`
operations. Those that are not implemented will raise an exception if
called.
"""
def __init__(self):
super().__init__()
@property
def plain(self):
return all(not isinstance(node, Tag) for node in self)
def __iter__(self):
return list.__iter__(self)
def __hash__(self):
return id(self)
def __add__(self, value):
raise NotImplementedError
def __eq__(self, value):
raise NotImplementedError
def __ge__(self, value):
raise NotImplementedError
def __gt__(self, value):
raise NotImplementedError
def __iadd__(self, value):
raise NotImplementedError
def __imul__(self, value):
raise NotImplementedError
def __le__(self, value):
raise NotImplementedError
def __lt__(self, value):
raise NotImplementedError
def __mul__(self, value):
raise NotImplementedError
def __ne__(self, value):
raise NotImplementedError
def __rmul__(self, value):
raise NotImplementedError
def count(self, value):
raise NotImplementedError
def pop(self, index: SupportsIndex=-1):
node = self[index]
del self[index]
return node
def extend(self, iterable):
for node in list(iterable):
self.append(node)
def coalesce(self, recursive=True):
i = 0
while i < len(self):
cur = self[i]
if isinstance(cur, String):
if not cur.data:
cur.delete()
elif i < len(self) - 1 and isinstance(self[i + 1], String):
cur.replace_with(cur.data + self[i + 1].data)
self[i + 1].delete()
else:
i += 1
elif recursive and isinstance(cur, Tag):
cur.coalesce()
i += 1
else:
i += 1
def stuck_child(self):
i = 0
while i < len(self):
node = self[i]
match node:
case Tag():
return node
case String() if node.isspace():
pass
case Comment() | Instruction():
pass
case _:
break
i += 1
def index(self, node, start: SupportsIndex=0, stop: SupportsIndex=sys.maxsize):
"""Note that we check for objects identity: we compare pointers
instead of using __eq__. This kinda breaks semantics, but we
want to be able to compare String nodes with the usual operator.
"""
start = self._translate_index(start)
stop = self._translate_index(stop)
while start < stop:
if self[start] is node:
return start
start += 1
raise ValueError("not found")
def __contains__(self, node):
"""Note that we check for objects identity. We compare pointers
instead of using __eq__.
"""
for child in self:
if child is node:
return True
return False
def children(self):
ret = []
for node in self:
if isinstance(node, Tag):
ret.append(node)
return ret
@property
def mixed(self):
has_string = has_tag = False
for node in self:
match node:
case Tag():
if has_string:
return True
has_tag = True
case String() if not node.isspace():
if has_tag:
return True
has_string = True
return False
@property
def empty(self):
for node in self:
match node:
case Tag():
return False
case String() if not node.isspace():
return False
return True
def remove(self, node):
"Removes the given child node."
i = self.index(node)
del self[i]
def clear(self):
while len(self) > 0:
del self[0]
def __setitem__(self, key, value):
assert isinstance(key, int)
self[key].replace_with(value)
def __delitem__(self, i):
node = self[i]
node._parent = None
node.location = None
list.__delitem__(self, i)
def _translate_index(self, i):
if i < 0:
i += len(self)
if i < 0:
i = 0
elif i > len(self):
i = len(self)
return i
def insert(self, i, node):
if isinstance(node, Node):
if isinstance(node, Tree):
for j, child in enumerate(list(node)):
self.insert(i + j, child)
return
# Detach the node from the tree it belongs to, if any.
# The node might already belong to this tree.
node.delete()
else:
assert isinstance(node, str), repr(node)
node = String(node)
i = self._translate_index(i)
node._parent = self
list.insert(self, i, node)
def append(self, node: Node | str):
self.insert(len(self), node)
def prepend(self, node):
self.insert(0, node)
def strings(self):
ret = []
for node in self:
match node:
case String():
ret.append(node)
case Tag():
ret.extend(node.strings())
return ret
class Tree(Branch):
"""`Tree` represents the XML document proper. It must contain a single
tag node and optionally comments and processing instructions. `Tree`
objects constructed from files also hold blank `String` nodes for
new lines, etc.
"""
def __init__(self):
# Prevent initializing this with an iterator, because we don't
# do this in Tag.
super().__init__()
self._byte_source = None
self.location = None
self._file = None
def __hash__(self):
return id(self)
@property
def path(self):
return "/"
@property
def parent(self):
return None
@property
def file(self):
return self._file
@property
def root(self):
ret = None
for node in self:
if isinstance(node, Tag):
if ret is not None:
raise Exception("multiple root tags in XML document")
ret = node
if ret is None:
raise Exception("attempt to retrieve the root tag of a tree that does not have one")
return ret
@property
def byte_source(self):
return self._byte_source
def __repr__(self):
if self.file:
return f"<Tree file={self.file!r}>"
return "<Tree>"
def text(self, **kwargs):
return "".join(node.text(**kwargs) for node in self)
def delete(self):
raise Exception("nodes of type 'tree' cannot be deleted")
def insert_before(self, node):
raise Exception("cannot insert a node before a tree")
def insert_after(self, node):
raise Exception("cannot insert a node after a tree")
def copy(self):
ret = Tree()
for node in self:
ret.append(node.copy())
return ret
def replace_with(self, other):
raise Exception("cannot replace Tree nodes")
class Tag(Branch):
"""Represents element nodes.
`Tag` objects have both a `list`-like and a `dict`-like interface.
When they are indexed with integers, the children of the node are
accessed. When they are indexed with strings, XML attributes are
accessed. Indexing an attribute that the `Tag` does not possess is
not treated as an error, and returns the empty string.
The `in` operator also takes types into account: if a `Node` is given,
it will check whether this node is a child of `Tag`. Otherwise, it
assumes the argument is an attribute name, and checks whether the
`Tag` bears this attribute.
Iterating over a `Tag` node yields the tag's children. The methods
`keys()`, `values()` and `items()` can be used for iterating over
attributes.
"""
__match_args__ = ("name",)
def __init__(self, name_, **attributes):
"""The argument `name` is the name of the node as a string, e.g.
"html". Attributes can be passed as keyword arguments with
`**attributes` (their order is preserved, see
https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep468).
"""
super().__init__()
self.name = name_
self.attrs = collections.OrderedDict()
self.problems = []
for key, value in attributes.items():
# Special case, for passing python keywords conveniently,
# as in tree.Tag("span", class_="hello"), which can be
# used instead of tree.Tag("span", **{"class": "hello"})
if len(key) > 1 and key[-1] == "_":
key = key[:-1]
# So that we can use tree.Tag("span", data_tip="foo")
# instead of tree.Tag("span", **{"data-tip": "foo"})
key = key.replace("_", "-")
self[key] = value
def stuck_following_sibling(self):
parent = self.parent
assert parent is not None
i = parent.index(self) + 1
while i < len(parent):
node = parent[i]
match node:
case Tag():
return node
case String() if node.isspace():
pass
case Comment() | Instruction():
pass
case _:
break
i += 1
def stuck_preceding_sibling(self):
parent = self.parent
assert parent is not None
i = parent.index(self) - 1
while i >= 0:
node = parent[i]
match node:
case Tag():
return node
case String() if node.isspace():
pass
case Comment() | Instruction():
pass
case _:
break
i -= 1
def __hash__(self):
return id(self)
def copy(self):
ret = Tag(self.name, **self.attrs)
ret.notes = self.notes.copy()
for child in self:
ret.append(child.copy())
return ret
def keys(self):
return self.attrs.keys()
def values(self):
return self.attrs.values()
def items(self):
return self.attrs.items()
def __repr__(self):
ret = f"<{self.name}"
for k, v in self.attrs.items():
ret += f' {k}={quote_attribute(v)}'
ret += ">"
return ret
def __contains__(self, val):
if isinstance(val, Node):
return super().__contains__(val)
assert isinstance(val, str)
return val in self.attrs
def unwrap(self):
parent = self.parent
i = parent.index(self)
list.__delitem__(parent, i)
for p, node in enumerate(self, i):
node._parent = parent
list.insert(parent, p, node)
self._parent = None
self.location = None
list.clear(self)
return self
@property
def path(self):
buf = []
node = self
while not isinstance(node, Tree):
parent = node.parent
index = 0
for child in parent:
if not isinstance(child, Tag):
continue
if child.name == node.name:
index += 1
if child is node:
break
assert index > 0
buf.append(f"/{node.name}[{index}]")
node = parent
assert buf
buf.reverse()
return "".join(buf)
def __getitem__(self, key):
if isinstance(key, str):
return self.attrs.get(key, "")
return super().__getitem__(key)
def __setitem__(self, key, value):
if isinstance(key, int):
return super().__setitem__(key, value)
assert isinstance(key, str)
if value is None:
del self[key]
return
value = str(value)
# Always normalize space.
value = " ".join(value.strip().split())
if value:
self.attrs[key] = value
elif key in self.attrs:
del self.attrs[key]
def __delitem__(self, key):
if isinstance(key, int):
super().__delitem__(key)
else:
assert isinstance(key, str)
try:
del self.attrs[key]
except KeyError:
pass
def text(self, **kwargs):
buf = []
config = kwargs.copy()
config["space"] = "preserve"
for node in self:
buf.append(node.text(**config))
data = "".join(buf)
if kwargs.get("space", "default") == "default":
data = re.sub(r"\s+", " ", data.strip())
return data
class String(Node, collections.UserString):
"""Represents a text node.
`String` nodes behave like normal `str` objects, but they can also be
edited in-place with the following methods."""
def clear(self):
"Sets this `String` to the empty string."
if self.data == "":
return
self.location = None
self.data = ""
def __hash__(self):
return id(self)
@property
def plain(self):
return True
def strings(self):
return [self]
def append(self, data):
"Adds text at the end of this `String`."
if not data:
return
self.location = None
self.data += data
def prepend(self, data):
"Adds text at the beginning of this `String`."
if not data:
return
self.location = None
self.data = data + self.data