add tempDir logic to gracefully rename the parent folder in a collection. fix: EPERM

This commit is contained in:
Pragadesh-45 2024-10-01 15:00:55 +05:30
parent de2053f988
commit 1fe7af4fad

View File

@ -1,5 +1,7 @@
const _ = require('lodash'); const _ = require('lodash');
const fs = require('fs'); const fs = require('fs');
const fsExtra = require('fs-extra');
const os = require('os');
const path = require('path'); const path = require('path');
const { ipcMain, shell, dialog, app } = require('electron'); const { ipcMain, shell, dialog, app } = require('electron');
const { envJsonToBru, bruToJson, jsonToBru, jsonToCollectionBru } = require('../bru'); const { envJsonToBru, bruToJson, jsonToBru, jsonToCollectionBru } = require('../bru');
@ -17,7 +19,8 @@ const {
isWSLPath, isWSLPath,
normalizeWslPath, normalizeWslPath,
normalizeAndResolvePath, normalizeAndResolvePath,
safeToRename safeToRename,
isWindowsOS
} = require('../utils/filesystem'); } = require('../utils/filesystem');
const { openCollectionDialog } = require('../app/collections'); const { openCollectionDialog } = require('../app/collections');
const { generateUidBasedOnHash, stringifyJson, safeParseJSON, safeStringifyJSON } = require('../utils/common'); const { generateUidBasedOnHash, stringifyJson, safeParseJSON, safeStringifyJSON } = require('../utils/common');
@ -352,23 +355,31 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
const newBruFilePath = bruFile.replace(oldPath, newPath); const newBruFilePath = bruFile.replace(oldPath, newPath);
moveRequestUid(bruFile, newBruFilePath); moveRequestUid(bruFile, newBruFilePath);
} }
return fs.renameSync(oldPath, newPath);
if (isWindowsOS() && !isWSLPath(oldPath)) {
const tempDir = path.join(os.tmpdir(), `temp-folder-${Date.now()}`);
await fsExtra.copy(oldPath, tempDir);
await fsExtra.move(tempDir, newPath, { overwrite: true });
await fsExtra.remove(oldPath);
} else {
await fs.rename(oldPath, newPath);
}
return newPath;
} }
const isBru = hasBruExtension(oldPath); if (!hasBruExtension(oldPath)) {
if (!isBru) {
throw new Error(`path: ${oldPath} is not a bru file`); throw new Error(`path: ${oldPath} is not a bru file`);
} }
// update name in file and save new copy, then delete old copy // update name in file and save new copy, then delete old copy
const data = fs.readFileSync(oldPath, 'utf8'); const data = await fs.promises.readFile(oldPath, 'utf8'); // Use async read
const jsonData = bruToJson(data); const jsonData = bruToJson(data);
jsonData.name = newName; jsonData.name = newName;
moveRequestUid(oldPath, newPath); moveRequestUid(oldPath, newPath);
const content = jsonToBru(jsonData); const content = jsonToBru(jsonData);
await fs.unlinkSync(oldPath); await fs.promises.unlink(oldPath);
await writeFile(newPath, content); await writeFile(newPath, content);
return newPath; return newPath;