Skip to content

feat(collection): implement folder migration to YAML format with sequence preservation - #8610

Closed
utkarsh-bruno wants to merge 5 commits into
usebruno:mainfrom
utkarsh-bruno:fix/BRU-3854
Closed

utkarsh-bruno wants to merge 5 commits into
usebruno:mainfrom
utkarsh-bruno:fix/BRU-3854

Conversation

@utkarsh-bruno

@utkarsh-bruno utkarsh-bruno commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • [] I've used AI significantly to create this pull request
  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

Summary by CodeRabbit

  • New Features

    • Added migration support for converting .bru collections to the YML format.
    • Converts collections, folders, requests, and environments while preserving folder ordering.
    • Automatically updates collection metadata and remaps open collection tabs after migration.
  • Bug Fixes

    • Added rollback handling to clean up partially migrated files when migration fails.
    • Improved watcher recovery and error reporting during migration and collection import.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The 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.

Changes

Bru to YML migration

Layer / File(s) Summary
Derive and stamp folder migration items
packages/bruno-electron/src/ipc/migrate-bru-to-yml.js
Collects visible folders, loads metadata, normalizes folder data, and assigns contiguous sibling sequence values.
Integrate stamped folder conversion
packages/bruno-electron/src/ipc/collection.js
Writes precomputed folder.yml files, queues source folder.bru files for deletion, and removes inline folder conversion.
Register migration IPC workflow
packages/bruno-electron/src/ipc/migrate-bru-to-yml.js, packages/bruno-electron/src/index.js
Adds the migration handler, filesystem conversion, watcher/remount handling, rollback cleanup, and application startup registration.

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
Loading

Possibly related PRs

Suggested reviewers: helloanoop, lohit-bruno, bijin-bruno, sid-bruno, vijayh-bruno

Poem

Bru files gather, YAML takes flight,
Folders line up in sequence bright.
Watchers pause, then wake anew,
Tabs find paths they once knew.
Rollback guards the migration crew.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: migrating collection folders to YAML while preserving sequence order.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/bruno-electron/src/ipc/migrate-folder-seq.js (1)

14-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Normalize paths upfront and remove redundant conditions.

The dirname and envDirPath are repeatedly normalized inside the loop, and the .startsWith check mixes a potentially unnormalized envDirPath with a raw dirname. Additionally, the folder.bru check does the exact same thing as the fallback (addAncestors(dirname)), so the if block 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

📥 Commits

Reviewing files that changed from the base of the PR and between e46f87f and 1906c42.

📒 Files selected for processing (2)
  • packages/bruno-electron/src/ipc/collection.js
  • packages/bruno-electron/src/ipc/migrate-folder-seq.js

naman-bruno
naman-bruno previously approved these changes Jul 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 lift

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1906c42 and 5f9a0ea.

📒 Files selected for processing (3)
  • packages/bruno-electron/src/index.js
  • packages/bruno-electron/src/ipc/collection.js
  • packages/bruno-electron/src/ipc/migrate-bru-to-yml.js
💤 Files with no reviewable changes (1)
  • packages/bruno-electron/src/ipc/collection.js

Comment on lines +236 to +291
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +263 to +265
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.`
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
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`.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants