diff --git a/pykeepass/entry.py b/pykeepass/entry.py index ced33884..e62c835c 100644 --- a/pykeepass/entry.py +++ b/pykeepass/entry.py @@ -118,6 +118,26 @@ def _get_string_field_keys(self, exclude_reserved=False): else: return results + @property + def index(self): + """int: get index of a entry within a group""" + group = self.group._element + children = group.getchildren() + first_index = self.group._first_entry + index = children.index(self._element) + return index - first_index + + def reindex(self, new_index): + """Move entry to a new index within a group + + Args: + new_index (int): new index for the entry starting at 0 + """ + group = self.group._element + first_index = self.group._first_entry + group.remove(self._element) + group.insert(new_index+first_index, self._element) + @property def attachments(self): return self._kp.find_attachments( diff --git a/pykeepass/group.py b/pykeepass/group.py index 6446ce18..3eabe08e 100644 --- a/pykeepass/group.py +++ b/pykeepass/group.py @@ -40,6 +40,12 @@ def __init__(self, name=None, element=None, icon=None, notes=None, 'element, but a {}'.format(element.tag) self._element = element + @property + def _first_entry(self): + children = self._element.getchildren() + first_element = next(e for e in children if e.tag == "Entry") + return children.index(first_element) + @property def name(self): """str: get or set group name""" diff --git a/tests/tests.py b/tests/tests.py index bcabe355..6f04009a 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -614,6 +614,17 @@ def test_is_custom_property_protected(self): self.assertFalse(e.is_custom_property_protected('not-protected')) self.assertFalse(e.is_custom_property_protected('non-existent')) + def test_reindex(self): + e1 = self.kp.add_entry(self.kp.root_group, 'Test-Index1', 'user-index', 'pass') + e2 = self.kp.add_entry(self.kp.root_group, 'Test-Index2', 'user-index', 'pass') + e3 = self.kp.add_entry(self.kp.root_group, 'Test-Index3', 'user-index', 'pass') + e4 = self.kp.add_entry(self.kp.root_group, 'Test-Index4', 'user-index', 'pass') + e2.reindex(0) + e3.reindex(0) + e4.reindex(0) + entries = self.kp.find_entries(username="user-index") + self.assertEqual(entries, [e4,e3,e2,e1]) + class EntryHistoryTests3(KDBX3Tests):