Repository navigation
fix(watcher): refresh open requests when a request file is replaced #217
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
andrea-spotsoftware
wants to merge
6
commits into
usebruno:main
Choose a base branch
from
andrea-spotsoftware:fix/reload-request-on-file-replace
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
05fdd1d
fix(watcher): refresh open requests when a request file is replaced
andrea-spotsoftware 53ebfb4
test(watcher): use node: imports and keep imports at the top
andrea-spotsoftware 5e184dc
fix(watcher): re-read replaced files only when open in an editor
andrea-spotsoftware 3417823
test(watcher): replace the request file for real in the test
andrea-spotsoftware e3a1d9a
fix(watcher): keep nested collection root files out of the full re-read
andrea-spotsoftware cb19447
test(watcher): make the nested fixture a real collection and share cl…
andrea-spotsoftware File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| import { describe, test, expect, vi, afterEach } from 'vitest'; | ||
| import fs from 'node:fs'; | ||
| import os from 'node:os'; | ||
| import path from 'node:path'; | ||
| import { CollectionWatcher, setMessageSender } from './collection-watcher'; | ||
| import { registerDocument, unregisterDocument } from '../editors/dirty-state-manager'; | ||
| import collectionsReducer, { | ||
| collectionAddFileEvent, | ||
| collectionChangeFileEvent | ||
| } from 'providers/ReduxStore/slices/collections'; | ||
|
|
||
| type Listener = (uri: { fsPath: string }) => Promise<void>; | ||
|
|
||
| const { createListeners } = vi.hoisted(() => ({ createListeners: new Map<string, Listener>() })); | ||
|
|
||
| vi.mock('vscode', async (importOriginal) => { | ||
| const original = await importOriginal<Record<string, unknown>>(); | ||
| return { | ||
| ...original, | ||
| RelativePattern: class { | ||
| constructor(public base: string, public pattern: string) {} | ||
| }, | ||
| workspace: { | ||
| ...(original.workspace as object), | ||
| createFileSystemWatcher: (glob: { pattern: string }) => ({ | ||
| onDidCreate: (listener: Listener) => createListeners.set(glob.pattern, listener), | ||
| onDidChange: vi.fn(), | ||
| onDidDelete: vi.fn(), | ||
| dispose: vi.fn() | ||
| }) | ||
| } | ||
| }; | ||
| }); | ||
|
|
||
| const COLLECTION_UID = 'collection-1'; | ||
|
|
||
| const request = (marker: string) => `meta { | ||
| name: sign in | ||
| type: http | ||
| seq: 1 | ||
| } | ||
|
|
||
| post { | ||
| url: https://example.com/login | ||
| body: none | ||
| auth: none | ||
| } | ||
|
|
||
| script:post-response { | ||
| console.log('${marker}'); | ||
| } | ||
| `; | ||
|
|
||
| let collectionPath: string; | ||
| let requestPath: string; | ||
| const pathsOpenInEditor: string[] = []; | ||
|
|
||
| const openInBrunoEditor = (filePath: string): void => { | ||
| registerDocument({ uri: { fsPath: filePath } } as never); | ||
| pathsOpenInEditor.push(filePath); | ||
| }; | ||
|
|
||
| const writeBrunoJson = (dir: string, name: string): void => { | ||
| fs.writeFileSync(path.join(dir, 'bruno.json'), JSON.stringify({ version: '1', name, type: 'collection' })); | ||
| }; | ||
|
|
||
| // A collection with one request whose post-response script logs 'v1'. | ||
| const createCollection = ({ openInEditor }: { openInEditor: boolean }): void => { | ||
| collectionPath = fs.mkdtempSync(path.join(os.tmpdir(), 'bruno-watcher-')); | ||
| writeBrunoJson(collectionPath, 'c'); | ||
| requestPath = path.join(collectionPath, 'sign-in.bru'); | ||
| fs.writeFileSync(requestPath, request('v1')); | ||
| if (openInEditor) { | ||
| openInBrunoEditor(requestPath); | ||
| } | ||
| }; | ||
|
|
||
| // Replaces the request file the way an atomic save does (new content renamed over the old file), | ||
| // then fires the create event VS Code reports for it. | ||
| const replaceRequestFile = async (marker: string): Promise<void> => { | ||
| const tempPath = `${requestPath}.tmp`; | ||
| fs.writeFileSync(tempPath, request(marker)); | ||
| fs.renameSync(tempPath, requestPath); | ||
| await createListeners.get('**/*.bru')!({ fsPath: requestPath }); | ||
| }; | ||
|
|
||
| type CollectionsState = ReturnType<typeof collectionsReducer>; | ||
|
|
||
| // Applies the tree updates sent by the extension to the collections reducer, as useIpcEvents does. | ||
| const applyTreeUpdates = (calls: unknown[][]): CollectionsState => { | ||
| const initialState = { | ||
| collections: [{ uid: COLLECTION_UID, name: 'c', pathname: collectionPath, items: [], environments: [], brunoConfig: {} }], | ||
| collectionSortOrder: 'default', | ||
| activeConnections: {} | ||
| } as unknown as CollectionsState; | ||
|
|
||
| return calls | ||
| .filter(([channel]) => channel === 'main:collection-tree-updated') | ||
| .reduce<CollectionsState>((state, [, type, payload]) => { | ||
| if (type === 'addFile') { | ||
| return collectionsReducer(state, collectionAddFileEvent(payload as never)); | ||
| } | ||
| if (type === 'change') { | ||
| return collectionsReducer(state, collectionChangeFileEvent(payload as never)); | ||
| } | ||
| return state; | ||
| }, initialState); | ||
| }; | ||
|
|
||
| const postResponseScript = (calls: unknown[][]): string | undefined => { | ||
| const item = applyTreeUpdates(calls).collections[0].items.find((i) => i.type === 'http-request'); | ||
| return item?.request?.script?.res; | ||
| }; | ||
|
|
||
| const metadataOnlyAdd = ['main:collection-tree-updated', 'addFile', expect.objectContaining({ partial: true })]; | ||
|
|
||
| afterEach(() => { | ||
| pathsOpenInEditor.splice(0).forEach(unregisterDocument); | ||
| fs.rmSync(collectionPath, { recursive: true, force: true }); | ||
| createListeners.clear(); | ||
| }); | ||
|
|
||
| describe('CollectionWatcher create events for request files', () => { | ||
| test('update a request open in an editor when its file is replaced', async () => { | ||
| createCollection({ openInEditor: true }); | ||
| const sent = vi.fn(); | ||
| setMessageSender(sent); | ||
| const watcher = new CollectionWatcher(); | ||
| // An editor loads its request in full before any change on disk. | ||
| await watcher.loadSingleRequest(requestPath, COLLECTION_UID, collectionPath, sent); | ||
| watcher.setupWatchersOnly(collectionPath, COLLECTION_UID); | ||
| expect(postResponseScript(sent.mock.calls)).toContain("console.log('v1')"); | ||
|
|
||
| await replaceRequestFile('v2'); | ||
|
|
||
| expect(postResponseScript(sent.mock.calls)).toContain("console.log('v2')"); | ||
| }); | ||
|
|
||
| test('send only the metadata when the replaced file is not open', async () => { | ||
| createCollection({ openInEditor: false }); | ||
| const sent = vi.fn(); | ||
| setMessageSender(sent); | ||
| new CollectionWatcher().setupWatchersOnly(collectionPath, COLLECTION_UID); | ||
|
|
||
| await replaceRequestFile('v2'); | ||
|
|
||
| expect(sent.mock.calls).toEqual([metadataOnlyAdd]); | ||
| }); | ||
|
|
||
| test('keep the nested collection marker on a create event for a nested collection root file open in an editor', async () => { | ||
| createCollection({ openInEditor: false }); | ||
| const nestedPath = path.join(collectionPath, 'nested'); | ||
| fs.mkdirSync(nestedPath); | ||
| writeBrunoJson(nestedPath, 'nested'); | ||
| const nestedRootPath = path.join(nestedPath, 'collection.bru'); | ||
| fs.writeFileSync(nestedRootPath, 'meta {\n name: nested\n}\n'); | ||
| openInBrunoEditor(nestedRootPath); | ||
| const sent = vi.fn(); | ||
| setMessageSender(sent); | ||
| new CollectionWatcher().setupWatchersOnly(collectionPath, COLLECTION_UID); | ||
|
|
||
| await createListeners.get('**/*.bru')!({ fsPath: nestedRootPath }); | ||
|
|
||
| expect(sent.mock.calls).toEqual([ | ||
| ['main:collection-tree-updated', 'addFile', expect.objectContaining({ | ||
| error: { message: 'This is a nested collection, not a request.' } | ||
| })] | ||
| ]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do not refresh an open request through the create path when the replacement is empty.
For a registered request,
handleFileAddnow callshandleRequestFileChangeafterhandleRequestFile. When the replacement content is empty or whitespace-only,handleRequestFileChangesendsunlink. The webview then removes the item throughcollectionUnlinkFileEvent, and that removal discards the item'sdraft. The inspected code has no recovery path for the draft. Before this change, the same empty replacement left the item in the tree.Skip the
handleRequestFileChangecall in this path when the content is empty. The open item and its draft then stay in the tree. Non-empty replacements keep the full refresh, and the change reducer preserves the draft for them.The same empty-content
unlinkbranch also runs for ordinary change events. That behavior predates this PR and needs a separate change.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@andrea-spotsoftware can you please check this ?
Something like this should fix I think. Please do have a check