* Handles processing for a renamed file. * Updates data in the new collection, drops the old collection if name changed, * deletes the old index entry, and upserts the new index entry.
(db: Db, filepath: string, oldFilepath: string)
| 265 | * deletes the old index entry, and upserts the new index entry. |
| 266 | */ |
| 267 | async function _handleFileRenamed(db: Db, filepath: string, oldFilepath: string): Promise<void> { |
| 268 | const collectionName = getCollectionNameFromJsonFile(filepath); |
| 269 | const oldCollectionName = getCollectionNameFromJsonFile(oldFilepath); |
| 270 | |
| 271 | console.log( |
| 272 | `\nProcessing Renamed file ${oldFilepath} -> ${filepath} ` + |
| 273 | `(Collections: ${oldCollectionName || 'N/A'} -> ${collectionName || 'N/A'})...` |
| 274 | ); |
| 275 | |
| 276 | // 1. Update data in the *new* collection (if applicable) |
| 277 | if (collectionName) { |
| 278 | const currentData = await readFileContent(filepath); |
| 279 | const oldFileContentString = await getOldFileContent(oldFilepath); // Get content from OLD git path |
| 280 | const oldData = parseJsonArrayContent(oldFileContentString, `HEAD~1:${oldFilepath}`); |
| 281 | |
| 282 | const { operations, skippedRecords } = calculateBulkOperations(oldData, currentData, filepath); |
| 283 | await executeBulkWrite(db, collectionName, operations); |
| 284 | |
| 285 | if (skippedRecords > 0) { |
| 286 | console.warn( |
| 287 | `Skipped ${skippedRecords} records in ${filepath} due to missing 'index' field.` |
| 288 | ); |
| 289 | } |
| 290 | } else { |
| 291 | console.warn(`Could not determine new collection name for ${filepath}. Skipping data update.`); |
| 292 | } |
| 293 | |
| 294 | // 2. Drop the *old* collection if its name was valid and different from the new one |
| 295 | if (oldCollectionName && oldCollectionName !== collectionName) { |
| 296 | console.log(`Dropping old collection '${oldCollectionName}' due to rename...`); |
| 297 | try { |
| 298 | await db.collection(oldCollectionName).drop(); |
| 299 | console.log(`Dropped old collection '${oldCollectionName}'.`); |
| 300 | } catch (err) { |
| 301 | if (!(err instanceof MongoServerError && err.codeName === 'NamespaceNotFound')) { |
| 302 | console.error(`Error dropping old collection '${oldCollectionName}' during rename:`, err); |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | // 3. Update index collections (delete old, upsert new) |
| 308 | // First delete the old index entry using the old path |
| 309 | await updateIndexCollection(db, oldFilepath, 'delete'); |
| 310 | // Then upsert the new index entry using the new path |
| 311 | await updateIndexCollection(db, filepath, 'upsert'); |
| 312 | } |
| 313 | |
| 314 | /** |
| 315 | * Handles processing for a deleted file. |
no test coverage detected