Repository navigation
feat(collection): implement folder migration to YAML format with sequence preservation - #8610
utkarsh-bruno wants to merge 5 commits into
Conversation
WalkthroughThe Electron app adds an IPC handler for converting Bru collections to YML, including stamped folder ordering, file cleanup, watcher recovery, rollback handling, and runtime registration. The existing collection migration now uses precomputed folder migration items. ChangesBru to YML migration
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Renderer
participant MigrationIPC
participant CollectionFilesystem
participant CollectionWatcher
participant SnapshotManager
Renderer->>MigrationIPC: invoke renderer:migrate-collection-to-yml
MigrationIPC->>CollectionWatcher: remove watcher
MigrationIPC->>CollectionFilesystem: write collection, folder, request, and environment YAML
MigrationIPC->>CollectionFilesystem: delete converted Bru files and bruno.json
MigrationIPC->>SnapshotManager: remap collection tab paths
MigrationIPC->>CollectionWatcher: remount or re-attach watcher
MigrationIPC-->>Renderer: return migration result or error
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/bruno-electron/src/ipc/migrate-folder-seq.js (1)
14-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNormalize paths upfront and remove redundant conditions.
The
dirnameandenvDirPathare repeatedly normalized inside the loop, and the.startsWithcheck mixes a potentially unnormalizedenvDirPathwith a rawdirname. Additionally, thefolder.brucheck does the exact same thing as the fallback (addAncestors(dirname)), so theifblock is redundant.Consider this simplification to improve efficiency and OS-separator robustness:
♻️ Proposed refactor
- const addAncestors = (dirPath) => { - let current = path.normalize(dirPath); - while (current.startsWith(normalizedCollection) && current !== normalizedCollection) { - folders.add(current); - current = path.dirname(current); - } - }; - - for (const bruFilePath of bruFiles) { - const basename = path.basename(bruFilePath); - const dirname = path.dirname(bruFilePath); - - if (basename === 'collection.bru' && path.normalize(dirname) === normalizedCollection) { - continue; - } - if (path.normalize(dirname) === path.normalize(envDirPath) || dirname.startsWith(envDirPath + path.sep)) { - continue; - } - - if (basename === 'folder.bru') { - addAncestors(dirname); - continue; - } - - addAncestors(dirname); - } + const normalizedEnvDir = path.normalize(envDirPath); + + const addAncestors = (dirPath) => { + let current = dirPath; + while (current.startsWith(normalizedCollection) && current !== normalizedCollection) { + folders.add(current); + current = path.dirname(current); + } + }; + + for (const bruFilePath of bruFiles) { + const basename = path.basename(bruFilePath); + const dirname = path.normalize(path.dirname(bruFilePath)); + + if (basename === 'collection.bru' && dirname === normalizedCollection) { + continue; + } + if (dirname === normalizedEnvDir || dirname.startsWith(normalizedEnvDir + path.sep)) { + continue; + } + + addAncestors(dirname); + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-electron/src/ipc/migrate-folder-seq.js` around lines 14 - 39, Normalize each BRU file’s dirname once before the filtering logic, and normalize envDirPath once before the loop so both equality and descendant checks use normalized paths consistently. Remove the redundant basename === 'folder.bru' branch and retain a single addAncestors(dirname) call after the collection and environment-directory exclusions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@packages/bruno-electron/src/ipc/migrate-folder-seq.js`:
- Around line 14-39: Normalize each BRU file’s dirname once before the filtering
logic, and normalize envDirPath once before the loop so both equality and
descendant checks use normalized paths consistently. Remove the redundant
basename === 'folder.bru' branch and retain a single addAncestors(dirname) call
after the collection and environment-directory exclusions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 06d3c42b-037d-4b0e-bb42-578cfdb504ac
📒 Files selected for processing (2)
packages/bruno-electron/src/ipc/collection.jspackages/bruno-electron/src/ipc/migrate-folder-seq.js
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/bruno-electron/src/ipc/migrate-bru-to-yml.js (1)
123-292: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftConsider adding test coverage for this migration path.
This handler performs destructive filesystem operations (deletes originals, rewrites config) with no accompanying tests in the provided changes. Given the failure modes above, unit tests around the rollback path and folder-seq stamping would materially reduce risk here.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-electron/src/ipc/migrate-bru-to-yml.js` around lines 123 - 292, The migration handler registerMigrateBruToYmlIpc lacks test coverage for its destructive and rollback behavior. Add focused tests covering successful folder sequence stamping through buildStampedFolderMigrateItems and failure recovery in the handler, including removal of newly written YML files and restarting the original watcher/configuration; mock filesystem, parsing, writing, and remount dependencies without changing production behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-electron/src/ipc/migrate-bru-to-yml.js`:
- Around line 263-265: Guard the `mainWindow.webContents.send` call in the
migration error-notification path so it only runs when `mainWindow` and its web
contents are still available and not destroyed. Preserve the existing error
message and migration rollback flow, while preventing a closed window from
throwing inside the outer `try`.
- Around line 236-291: Restructure the successful migration flow so all fallible
work, including tab-path remapping, getCollectionStats, remountCollectionV2,
watcher recovery, and webContents.send, completes before deleting originals.
Update the bruFilesToDelete/brunoJsonPath deletion phase to handle each unlink
independently, collecting or reporting failures without aborting mid-loop or
triggering rollback that removes newly written YAML files. Preserve the outer
catch for failures before deletion, and ensure deletion errors are surfaced
without leaving partial migration state.
---
Nitpick comments:
In `@packages/bruno-electron/src/ipc/migrate-bru-to-yml.js`:
- Around line 123-292: The migration handler registerMigrateBruToYmlIpc lacks
test coverage for its destructive and rollback behavior. Add focused tests
covering successful folder sequence stamping through
buildStampedFolderMigrateItems and failure recovery in the handler, including
removal of newly written YML files and restarting the original
watcher/configuration; mock filesystem, parsing, writing, and remount
dependencies without changing production behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 872d5794-9f3d-4b50-99d6-3306d1d00a0d
📒 Files selected for processing (3)
packages/bruno-electron/src/index.jspackages/bruno-electron/src/ipc/collection.jspackages/bruno-electron/src/ipc/migrate-bru-to-yml.js
💤 Files with no reviewable changes (1)
- packages/bruno-electron/src/ipc/collection.js
| for (const bruFile of bruFilesToDelete) { | ||
| fs.unlinkSync(bruFile); | ||
| } | ||
| fs.unlinkSync(brunoJsonPath); | ||
|
|
||
| try { | ||
| snapshotManager.remapCollectionTabPaths(collectionPathname, tabPathMap); | ||
| } catch (_) { | ||
| } | ||
|
|
||
| const { size, filesCount } = await getCollectionStats(collectionPathname); | ||
| ymlBrunoConfig.size = size; | ||
| ymlBrunoConfig.filesCount = filesCount; | ||
|
|
||
| try { | ||
| const remounted = await remountCollectionV2({ collectionUid, brunoConfig: ymlBrunoConfig }); | ||
| if (!remounted && watcher) { | ||
| watcher.addWatcher(mainWindow, collectionPathname, collectionUid, ymlBrunoConfig, false, undefined, { ignoreInitial: true }); | ||
| } | ||
| } catch (watcherError) { | ||
| console.error('Failed to re-attach watcher after migration:', watcherError); | ||
| try { | ||
| if (watcher) { | ||
| watcher.addWatcher(mainWindow, collectionPathname, collectionUid, ymlBrunoConfig, false, undefined, { ignoreInitial: true }); | ||
| } | ||
| } catch (fallbackError) { | ||
| console.error('Fallback watcher attach failed after migration:', fallbackError); | ||
| mainWindow.webContents.send('main:display-error', { | ||
| message: `Collection migrated to yml, but live sync could not be re-enabled: ${fallbackError.message}. Please reopen the collection.` | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return ymlBrunoConfig; | ||
| } catch (error) { | ||
| for (const ymlFile of writtenYmlFiles) { | ||
| try { | ||
| if (fs.existsSync(ymlFile)) { | ||
| fs.unlinkSync(ymlFile); | ||
| } | ||
| } catch (_) { | ||
| } | ||
| } | ||
|
|
||
| // Restart the watcher on the original bru collection | ||
| try { | ||
| const config = JSON.parse(fs.readFileSync(path.join(collectionPathname, 'bruno.json'), 'utf8')); | ||
| const remounted = await remountCollectionV2({ collectionUid, brunoConfig: config }); | ||
| if (!remounted && watcher) { | ||
| watcher.addWatcher(mainWindow, collectionPathname, collectionUid, config); | ||
| } | ||
| } catch (watcherError) { | ||
| console.error('Failed to restart watcher after migration error:', watcherError); | ||
| } | ||
| throw error; | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy lift
Deletion happens before other fallible steps, and rollback can't undo it — risk of total data loss.
bruFilesToDelete/brunoJsonPath are unlinked (Lines 236-239) before getCollectionStats (Line 246, unguarded await) and before the watcher/notification recovery block (Lines 250-267). That block itself has an unguarded mainWindow.webContents.send(...) (Lines 263-265) that throws if the window was closed mid-migration. Any of these throwing propagates to the outer catch (Line 270), which only removes the newly written .yml files — it never restores the already-deleted .bru/bruno.json. Net result: the collection can end up with neither the original .bru files nor the new .yml files.
Additionally, the delete loop itself (Lines 236-238) isn't guarded per-item — if one unlinkSync throws mid-loop, some originals are gone, the rest survive, and the outer catch still wipes every written .yml, so items whose original was already deleted lose both copies.
Recommend restructuring so deletion of originals is the true last irreversible step: move getCollectionStats, tab remap, and any other fallible work before the delete loop, and make the delete loop resilient (collect/report per-file errors instead of aborting) rather than relying on catch-based rollback for something that can't be rolled back.
🛠️ Suggested reordering
- for (const bruFile of bruFilesToDelete) {
- fs.unlinkSync(bruFile);
- }
- fs.unlinkSync(brunoJsonPath);
-
- try {
- snapshotManager.remapCollectionTabPaths(collectionPathname, tabPathMap);
- } catch (_) {
- }
-
- const { size, filesCount } = await getCollectionStats(collectionPathname);
+ // Compute anything that can still fail BEFORE deleting originals,
+ // so deletion is the true point of no return.
+ const { size, filesCount } = await getCollectionStats(collectionPathname);
ymlBrunoConfig.size = size;
ymlBrunoConfig.filesCount = filesCount;
+
+ for (const bruFile of bruFilesToDelete) {
+ try {
+ fs.unlinkSync(bruFile);
+ } catch (unlinkError) {
+ console.error(`Failed to remove legacy file after migration: ${bruFile}`, unlinkError);
+ }
+ }
+ try {
+ fs.unlinkSync(brunoJsonPath);
+ } catch (unlinkError) {
+ console.error('Failed to remove bruno.json after migration:', unlinkError);
+ }
+
+ try {
+ snapshotManager.remapCollectionTabPaths(collectionPathname, tabPathMap);
+ } catch (_) {
+ }🧰 Tools
🪛 ast-grep (0.44.1)
[warning] 281-281: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.readFileSync(path.join(collectionPathname, 'bruno.json'), 'utf8')
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').
(detect-non-literal-fs-filename)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/bruno-electron/src/ipc/migrate-bru-to-yml.js` around lines 236 -
291, Restructure the successful migration flow so all fallible work, including
tab-path remapping, getCollectionStats, remountCollectionV2, watcher recovery,
and webContents.send, completes before deleting originals. Update the
bruFilesToDelete/brunoJsonPath deletion phase to handle each unlink
independently, collecting or reporting failures without aborting mid-loop or
triggering rollback that removes newly written YAML files. Preserve the outer
catch for failures before deletion, and ensure deletion errors are surfaced
without leaving partial migration state.
| mainWindow.webContents.send('main:display-error', { | ||
| message: `Collection migrated to yml, but live sync could not be re-enabled: ${fallbackError.message}. Please reopen the collection.` | ||
| }); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Guard mainWindow.webContents.send against a destroyed window.
If the window closes during the (multi-await) migration, mainWindow may already be destroyed, making this call throw. Since this whole block sits inside the outer try, that throw is what routes into the destructive rollback described above.
🛡️ Suggested guard
- mainWindow.webContents.send('main:display-error', {
- message: `Collection migrated to yml, but live sync could not be re-enabled: ${fallbackError.message}. Please reopen the collection.`
- });
+ if (mainWindow && !mainWindow.isDestroyed()) {
+ mainWindow.webContents.send('main:display-error', {
+ message: `Collection migrated to yml, but live sync could not be re-enabled: ${fallbackError.message}. Please reopen the collection.`
+ });
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| mainWindow.webContents.send('main:display-error', { | |
| message: `Collection migrated to yml, but live sync could not be re-enabled: ${fallbackError.message}. Please reopen the collection.` | |
| }); | |
| if (mainWindow && !mainWindow.isDestroyed()) { | |
| mainWindow.webContents.send('main:display-error', { | |
| message: `Collection migrated to yml, but live sync could not be re-enabled: ${fallbackError.message}. Please reopen the collection.` | |
| }); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/bruno-electron/src/ipc/migrate-bru-to-yml.js` around lines 263 -
265, Guard the `mainWindow.webContents.send` call in the migration
error-notification path so it only runs when `mainWindow` and its web contents
are still available and not destroyed. Preserve the existing error message and
migration rollback flow, while preventing a closed window from throwing inside
the outer `try`.
Description
Bru → yml migration was changing folder order on reopen when some folders had seq and others did not (or had no folder.bru).
During migration we now freeze the current sidebar order: collect every visible folder, sort with sortByNameThenSequence, stamp contiguous seq 1..N per parent, and write folder.yml for all of them.
Contribution Checklist:
Summary by CodeRabbit
New Features
.brucollections to the YML format.Bug Fixes