> Keep all existing XML content, only make granular updates.

ChatGPT notes that it's not doing it right:

> This updated version loads the existing XML content, removes the existing items, and adds the updated recent items. It preserves the rest of the XML structure.
This commit is contained in:
Isaiah Odhner 2023-06-27 18:25:58 -04:00
parent f397de47c6
commit 156270f4d5

View File

@ -84,23 +84,37 @@ def load_recent_files():
def save_recent_files(recent_files):
# Create the root element
root = ET.Element("RecentFiles")
# Add each recent item to the root element
for item in recent_files:
root.append(item)
# Serialize the XML document
xml_data = ET.tostring(root, encoding="utf-8")
# Lock the recent file for writing
with open(RECENT_FILE_PATH, "w") as file:
fcntl.lockf(file, fcntl.LOCK_EX)
with open(RECENT_FILE_PATH, "r+") as file:
try:
fcntl.lockf(file, fcntl.LOCK_EX)
# Try to read the existing content
content = file.read()
file.seek(0)
if content:
# Parse the XML document
root = ET.fromstring(content)
existing_items = root.findall("RecentItem")
# Remove existing items from the root element
for item in existing_items:
root.remove(item)
else:
# Create the root element if the file is empty
root = ET.Element("RecentFiles")
# Add each recent item to the root element
for item in recent_files:
root.append(item)
# Serialize the XML document
xml_data = ET.tostring(root, encoding="utf-8")
# Write the XML document to the file
file.write("<?xml version=\"1.0\"?>\n")
file.write(xml_data.decode())
file.truncate()
finally:
# Unlock the recent file after writing
fcntl.lockf(file, fcntl.LOCK_UN)