Skip to content

Commit

Permalink
preview: fix (again) the “live preview” feature
Browse files Browse the repository at this point in the history
This commit makes sure to only create one preview (the previous
tentative fix on live previews would create 1 preview, then a 2nd
preview, and then update that 2nd preview).

Follow-up to bump-sh#456 (cf bump-sh#182)
  • Loading branch information
paulRbr committed Oct 5, 2023
1 parent 01b40f0 commit b2900ad
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/commands/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ export default class Preview extends Command {

async run(): Promise<void> {
const { args, flags } = this.parse(Preview);
const currentPreview: PreviewResponse = await this.preview(args.FILE, flags.open);

await this.preview(args.FILE, flags.open);
if (flags.live) {
await this.waitForChanges(args.FILE, flags.open);
await this.waitForChanges(args.FILE, currentPreview);
}

return;
Expand Down Expand Up @@ -76,20 +76,19 @@ export default class Preview extends Command {
return response.data;
}

async waitForChanges(file: string, open: boolean): Promise<void> {
async waitForChanges(file: string, preview: PreviewResponse): Promise<void> {
const mutex = new Mutex();
let currentPreview: PreviewResponse | undefined = undefined;
let currentPreview: PreviewResponse = preview;

cli.action.start(`Waiting for changes on file ${file}...`);

watch(file, async () => {
if (!mutex.isLocked()) {
const release = await mutex.acquire();
const firstOpen = !currentPreview && open;

this.preview(file, firstOpen, currentPreview)
this.preview(file, false, currentPreview)
.then((preview) => {
currentPreview = currentPreview || preview;
currentPreview = preview;
cli.action.start(`Waiting for changes on file ${file}`);
})
.catch((err) => {
Expand Down
19 changes: 19 additions & 0 deletions test/commands/preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,25 @@ describe('preview subcommand', () => {
expect(stdout).to.match(/https:\/\/bump.sh\/preview\/123abc-cba321/);
});

test
.nock('https://bump.sh', (api) =>
api.post('/api/v1/previews').reply(201, {
id: '123abc-cba321',
expires_at: new Date(),
public_url: 'https://bump.sh/preview/123abc-cba321',
}),
)
.stdout()
.stderr()
.command(['preview', '--live', 'examples/valid/openapi.v3.json'])
.it('Creates a live preview and waits for file update', ({ stdout, stderr }) => {
expect(stderr).to.match(/Let's render a preview on Bump... done/);

expect(stdout).to.match(/preview is visible at/);
expect(stdout).to.match(/https:\/\/bump.sh\/preview\/123abc-cba321/);
expect(stderr).to.match(/Waiting for changes on file/);
});

test
.nock('http://example.org', (api) => {
api
Expand Down

0 comments on commit b2900ad

Please sign in to comment.