Use the same method to generate item handles as for status keys

This commit is contained in:
Veronica Berglyd Olsen
2022-04-20 21:44:45 +02:00
parent ca76cb2af3
commit 8320aab1bf
+8 -33
View File
@@ -24,11 +24,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
""" """
import os import os
import random
import logging import logging
from time import time
from lxml import etree from lxml import etree
from hashlib import sha256
from novelwriter.enum import nwItemType, nwItemClass, nwItemLayout from novelwriter.enum import nwItemType, nwItemClass, nwItemLayout
from novelwriter.error import logException from novelwriter.error import logException
@@ -55,9 +54,6 @@ class NWTree():
self._theIndex = 0 # The current iterator index self._theIndex = 0 # The current iterator index
self._treeChanged = False # True if tree structure has changed self._treeChanged = False # True if tree structure has changed
self._handleSeed = None # Used for generating handles for testing
self._handleCount = 0 # A counter that is added to the handle generator
return return
## ##
@@ -340,14 +336,6 @@ class NWTree():
return return
def setSeed(self, theSeed):
"""Used for debugging!
Sets a seed for generating handles so that they always come out
in a predictable order.
"""
self._handleSeed = theSeed
return
def setFileItemLayout(self, tHandle, itemLayout): def setFileItemLayout(self, tHandle, itemLayout):
"""Set the nwItemLayout for a specific file. """Set the nwItemLayout for a specific file.
""" """
@@ -474,29 +462,16 @@ class NWTree():
self.theProject.setProjectChanged(True) self.theProject.setProjectChanged(True)
return return
def _makeHandle(self, addSeed=""): def _makeHandle(self):
"""Generate a unique item handle. In the event that the key """Generate a unique item handle. In the event that the key
already exists, salt the seed and generate a new handle. already exists, generate a new one.
A key collision is very unlikely to be caused by the truncation
of the sha256 hash to 13 characters. Assuming it is near-random,
it will on average happen every 4.5^15 times. However, the clock
seed is likely to occasionally generate a collision if the
handle requests come faster than the clock resolution.
""" """
if self._handleSeed is None: logger.verbose("Generating new handle")
newSeed = "%s_%d_%s" % (str(time()), self._handleCount, addSeed) handle = f"{random.getrandbits(52):013x}"
self._handleCount += 1 if handle in self._projTree:
else:
# This is used for debugging
newSeed = str(self._handleSeed)
self._handleSeed += 1
logger.verbose("Generating handle with seed '%s'", newSeed)
itemHandle = sha256(newSeed.encode()).hexdigest()[0:13]
if itemHandle in self._projTree:
logger.warning("Duplicate handle encountered! Retrying ...") logger.warning("Duplicate handle encountered! Retrying ...")
itemHandle = self._makeHandle(addSeed+"!") handle = self._makeHandle()
return itemHandle return handle
# END Class NWTree # END Class NWTree