From 41ff4aa455e617d38978cb4ec553ff06675da0f5 Mon Sep 17 00:00:00 2001 From: Colin Brown Date: Fri, 6 Mar 2026 20:00:17 +0000 Subject: [PATCH] fix: update removeAllEmptyDirs function to prevent root deletion and improve directory traversal --- backend/src/routes/proceed.ts | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/backend/src/routes/proceed.ts b/backend/src/routes/proceed.ts index 7b0302c..6c2feee 100644 --- a/backend/src/routes/proceed.ts +++ b/backend/src/routes/proceed.ts @@ -36,15 +36,31 @@ function removeEmptyDirs(dir: string, stopAt: string): void { } } -// Recursively remove ALL empty directories inside root (post-order traversal) -function removeAllEmptyDirs(dir: string): void { +// Recursively remove ALL empty directories inside root (post-order traversal), +// but never remove root itself. +function removeAllEmptyDirs(dir: string, stopAt: string): void { + if (dir === stopAt) { + // Clean up children but never delete the root itself + try { + const entries = fs.readdirSync(dir); + for (const entry of entries) { + const full = path.join(dir, entry); + try { + if (fs.statSync(full).isDirectory()) { + removeAllEmptyDirs(full, stopAt); + } + } catch { /* skip unreadable entries */ } + } + } catch { /* skip if dir is unreadable */ } + return; + } try { const entries = fs.readdirSync(dir); for (const entry of entries) { const full = path.join(dir, entry); try { if (fs.statSync(full).isDirectory()) { - removeAllEmptyDirs(full); + removeAllEmptyDirs(full, stopAt); } } catch { /* skip unreadable entries */ } } @@ -87,7 +103,7 @@ router.post('/', (req: Request, res: Response) => { const processNext = (i: number): void => { if (i >= rows.length) { if (deleteEmptyFolders) { - removeAllEmptyDirs(sourceDir); + removeAllEmptyDirs(sourceDir, sourceDir); } emit({ type: 'done', ...result }); res.end();