Skip to content

Commit da56f4c

Browse files
committed
Add indented group printing from dungscout96
1 parent 0689ad5 commit da56f4c

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

hed/models/hed_group.py

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@ def sorted(self):
157157
sorted_copy (HedGroup): The sorted copy
158158
"""
159159
string_copy = self.copy()
160-
return string_copy._sorted(update_self=True)
160+
string_copy._sorted(update_self=True)
161+
return string_copy
161162

162163
def _sorted(self, update_self=False):
163164
""" Returns a sorted copy of this hed group as a list of it's children
@@ -350,6 +351,39 @@ def lower(self):
350351
""" Convenience function, equivalent to str(self).lower() """
351352
return str(self).lower()
352353

354+
def get_as_indented(self, tag_attribute="short_tag"):
355+
"""Returns the string as a multiline indented format
356+
357+
Parameters:
358+
tag_attribute (str): The hed_tag property to use to construct the string (usually short_tag or long_tag).
359+
360+
Returns:
361+
formatted_hed (str): the indented string
362+
"""
363+
hed_string = self.sorted().get_as_form(tag_attribute)
364+
365+
level_open = []
366+
level = 0
367+
indented = ""
368+
prev = ''
369+
for c in hed_string:
370+
if c == "(":
371+
level_open.append(level)
372+
indented += "\n" + "\t" * level + c
373+
level += 1
374+
elif c == ")":
375+
level = level_open.pop()
376+
if prev == ")":
377+
indented += "\n" + "\t" * level + c
378+
else:
379+
indented += c
380+
381+
else:
382+
indented += c
383+
prev = c
384+
385+
return indented
386+
353387
def find_placeholder_tag(self):
354388
""" Return a placeholder tag, if present in this group.
355389

tests/models/test_hed_group.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from hed import schema
55
from hed.models import HedString
6+
import copy
67

78

89
class Test(unittest.TestCase):
@@ -121,5 +122,15 @@ def test_sort_and_sorted(self):
121122
]
122123
self._compare_strings(hed_strings)
123124

125+
def test_sorted_structure(self):
126+
hed_string = HedString("(Tag3, Tag1, Tag5, Tag2, Tag4)", self.hed_schema)
127+
original_hed_string = copy.deepcopy(hed_string)
128+
129+
sorted_hed_string = hed_string.sorted()
130+
131+
self.assertIsInstance(sorted_hed_string, HedString)
132+
self.assertEqual(str(original_hed_string), str(hed_string))
133+
self.assertIsNot(sorted_hed_string, hed_string)
134+
124135
if __name__ == '__main__':
125136
unittest.main()

0 commit comments

Comments
 (0)