metadataUtils.js
1 const fs = require('fs').promises; 2 const path = require('path'); 3 4 async function readMetadata(dreamVaultPath, repoName) { 5 const metadataPath = path.join(dreamVaultPath, repoName, '.pl'); 6 try { 7 const data = await fs.readFile(metadataPath, 'utf8'); 8 return JSON.parse(data); 9 } catch (error) { 10 if (error.code === 'ENOENT') { 11 // If the file doesn't exist, return an empty object 12 return {}; 13 } 14 throw error; 15 } 16 } 17 18 async function writeMetadata(dreamVaultPath, repoName, metadata) { 19 const metadataPath = path.join(dreamVaultPath, repoName, '.pl'); 20 await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2), 'utf8'); 21 } 22 23 async function updateBidirectionalRelationships(dreamVaultPath, currentRepoName, oldMetadata, newMetadata) { 24 const oldRelatedNodes = oldMetadata.relatedNodes || []; 25 const newRelatedNodes = newMetadata.relatedNodes || []; 26 27 const addedNodes = newRelatedNodes.filter(node => !oldRelatedNodes.includes(node)); 28 const removedNodes = oldRelatedNodes.filter(node => !newRelatedNodes.includes(node)); 29 30 for (const nodeName of addedNodes) { 31 await updateRelatedNode(dreamVaultPath, nodeName, currentRepoName, true); 32 } 33 34 for (const nodeName of removedNodes) { 35 await updateRelatedNode(dreamVaultPath, nodeName, currentRepoName, false); 36 } 37 } 38 39 async function updateRelatedNode(dreamVaultPath, nodeName, currentRepoName, isAdding) { 40 const nodeMetadataPath = path.join(dreamVaultPath, nodeName, '.pl'); 41 try { 42 const data = await fs.readFile(nodeMetadataPath, 'utf8'); 43 const metadata = JSON.parse(data); 44 45 if (!metadata.relatedNodes) { 46 metadata.relatedNodes = []; 47 } 48 49 if (isAdding && !metadata.relatedNodes.includes(currentRepoName)) { 50 metadata.relatedNodes.push(currentRepoName); 51 } else if (!isAdding) { 52 metadata.relatedNodes = metadata.relatedNodes.filter(name => name !== currentRepoName); 53 } 54 55 await fs.writeFile(nodeMetadataPath, JSON.stringify(metadata, null, 2), 'utf8'); 56 } catch (error) { 57 console.error(`Error updating related node ${nodeName}:`, error); 58 // Continue with other updates even if one fails 59 } 60 } 61 62 module.exports = { 63 updateBidirectionalRelationships, 64 readMetadata, 65 writeMetadata 66 };