Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 33 additions & 8 deletions src/github/pullRequestOverview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,20 +555,37 @@ export class PullRequestOverviewPanel extends IssueOverviewPanel<PullRequestMode
this._item = pullRequestModel;
this._diffLinkHashMapPromise = undefined;
const updateSequence = ++this._updateSequence;
const overviewIdentity = this._identity;
// An earlier load must not overwrite a closed panel or a newer request.
const isStale = () => this.isDisposed || updateSequence !== this._updateSequence
|| overviewIdentity !== this._identity || this._pendingUpdate !== undefined;
this._stackLoaded = false;
this._isBranchUpToDateWithBase = undefined;
const branchStatusSequence = ++this._branchStatusSequence;
const updateStart = performance.now();
this._stackPrefetch = undefined;
if (this._panel.visible) {
// The stack only needs the pull request, so it loads while the rest of the page does, and is shown once the page is.
const data = this.fetchStackData(pullRequestModel);
// A failure is reported when the stack is shown.
data.catch(() => undefined);
this._stackPrefetch = { updateSequence, data };
}

try {
// PR list models may contain Markdown without rendered description HTML.
// Resolve it before the initial webview context is sent.
if (pullRequestModel.body?.trim() && !pullRequestModel.bodyHTML?.trim()) {
// Preview data is detached from the shared model cache until freshness is checked.
const description = await pullRequestModel.githubRepository.getPullRequestPreview(pullRequestModel.number);
if (isStale()) {
return;
}
Comment thread
JFWooten4 marked this conversation as resolved.
Resolved
pullRequestModel.bodyHTML = description.bodyHTML;
pullRequestModel.update({ ...pullRequestModel.item, body: description.body, bodyHTML: description.bodyHTML });
}

if (this._panel.visible) {
// The stack only needs the pull request, so it loads while the rest of the page does, and is shown once the page is.
const data = this.fetchStackData(pullRequestModel);
// A failure is reported when the stack is shown.
data.catch(() => undefined);
this._stackPrefetch = { updateSequence, data };
}

const dataTimings = new Map<string, number>();
const measure = async <T>(name: string, promise: Promise<T>): Promise<T> => {
const start = performance.now();
Expand All @@ -592,6 +609,9 @@ export class PullRequestOverviewPanel extends IssueOverviewPanel<PullRequestMode
currentUser,
viewerCanEdit,
] = await updatingPromise;
if (isStale()) {
return;
}
const pullRequest = pullRequestModel;
const timelineEvents = cachedTimelineEvents;
const dataLoadDuration = performance.now() - updateStart;
Expand Down Expand Up @@ -631,6 +651,9 @@ export class PullRequestOverviewPanel extends IssueOverviewPanel<PullRequestMode
closingIssuesPromise,
this.getInitialStack(pullRequest),
]);
if (isStale()) {
return;
}
const contextDuration = performance.now() - contextStart;
this._canUpdateStackAccess = baseContext.hasWritePermission;
// Reloading the pull request keeps the recommendation that is shown, so that the page does not move,
Expand Down Expand Up @@ -812,7 +835,9 @@ export class PullRequestOverviewPanel extends IssueOverviewPanel<PullRequestMode
this._folderRepositoryManager.checkBranchUpToDate(pullRequest, true);
}
} catch (e) {
vscode.window.showErrorMessage(`Error updating pull request description: ${formatError(e)}`);
if (!isStale()) {
vscode.window.showErrorMessage(`Error updating pull request description: ${formatError(e)}`);
}
}
}

Expand Down
104 changes: 103 additions & 1 deletion src/test/github/pullRequestOverview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import { default as assert } from 'assert';
import * as vscode from 'vscode';
import { NetworkStatus } from 'apollo-boost';
import { SinonSandbox, SinonStub, createSandbox, match as sinonMatch } from 'sinon';

import { FolderRepositoryManager } from '../../github/folderRepositoryManager';
Expand Down Expand Up @@ -624,6 +625,7 @@ describe('PullRequestOverview', function () {
it(`initializes with the latest checkout state when ${initiallyCheckedOut ? 'leaving' : 'entering'} review mode during loading`, async function () {
const model = new PullRequestModel(credentialStore, telemetry, repo, remote,
convertRESTPullRequestToRawPullRequest(new PullRequestBuilder().number(1000).build(), repo));
model.bodyHTML = '<p>Please merge thx</p>';
const identity = { owner: remote.owner, repo: remote.repositoryName, number: model.number };
pullRequestManager.activePullRequest = initiallyCheckedOut ? model : undefined;
sinon.stub(pullRequestManager, 'getCurrentUser').resolves(model.author);
Expand Down Expand Up @@ -756,6 +758,7 @@ describe('PullRequestOverview', function () {
});

const prItem0 = convertRESTPullRequestToRawPullRequest(new PullRequestBuilder().number(1000).build(), repo);
prItem0.bodyHTML = '<p>Please merge thx</p>';
const prModel0 = new PullRequestModel(credentialStore, telemetry, repo, remote, prItem0);
const identity0 = { owner: prModel0.remote.owner, repo: prModel0.remote.repositoryName, number: prModel0.number };
const resolveStub = sinon.stub(pullRequestManager, 'resolvePullRequest').resolves(prModel0);
Expand Down Expand Up @@ -790,6 +793,8 @@ describe('PullRequestOverview', function () {
const firstModel = new PullRequestModel(credentialStore, telemetry, repo, remote, firstItem);
const updatedItem = convertRESTPullRequestToRawPullRequest(new PullRequestBuilder().number(1000).title('Updated title').build(), repo);
const updatedModel = new PullRequestModel(credentialStore, telemetry, repo, remote, updatedItem);
firstModel.bodyHTML = '<p>Please merge thx</p>';
updatedModel.bodyHTML = '<p>Please merge thx</p>';
const identity = { owner: firstModel.remote.owner, repo: firstModel.remote.repositoryName, number: firstModel.number };
let releaseInitialization: (defaultBranch: string) => void;
const blockedInitialization = new Promise<string>(resolve => releaseInitialization = resolve);
Expand Down Expand Up @@ -819,6 +824,8 @@ describe('PullRequestOverview', function () {
const firstModel = new PullRequestModel(credentialStore, telemetry, repo, remote, firstItem);
const updatedItem = convertRESTPullRequestToRawPullRequest(new PullRequestBuilder().number(1000).title('Updated title').build(), repo);
const updatedModel = new PullRequestModel(credentialStore, telemetry, repo, remote, updatedItem);
firstModel.bodyHTML = '<p>Please merge thx</p>';
updatedModel.bodyHTML = '<p>Please merge thx</p>';
const identity = { owner: firstModel.remote.owner, repo: firstModel.remote.repositoryName, number: firstModel.number };
const staleEvents: TimelineEvent[] = [];
let resolveTimeline: (events: TimelineEvent[]) => void;
Expand Down Expand Up @@ -875,6 +882,7 @@ describe('PullRequestOverview', function () {
});

const prItem0 = convertRESTPullRequestToRawPullRequest(new PullRequestBuilder().number(1000).build(), repo);
prItem0.bodyHTML = '<p>Please merge thx</p>';
const prModel0 = new PullRequestModel(credentialStore, telemetry, repo, remote, prItem0);
const identity0 = { owner: prModel0.remote.owner, repo: prModel0.remote.repositoryName, number: prModel0.number };
const resolveStub = sinon.stub(pullRequestManager, 'resolvePullRequest').resolves(prModel0);
Expand All @@ -889,6 +897,7 @@ describe('PullRequestOverview', function () {
assert.strictEqual(createWebviewPanel.callCount, 1);

const prItem1 = convertRESTPullRequestToRawPullRequest(new PullRequestBuilder().number(2000).build(), repo);
prItem1.bodyHTML = '<p>Please merge thx</p>';
const prModel1 = new PullRequestModel(credentialStore, telemetry, repo, remote, prItem1);
const identity1 = { owner: prModel1.remote.owner, repo: prModel1.remote.repositoryName, number: prModel1.number };
resolveStub.resolves(prModel1);
Expand Down Expand Up @@ -932,7 +941,8 @@ describe('PullRequestOverview', function () {

beforeEach(function () {
const prItem = convertRESTPullRequestToRawPullRequest(new PullRequestBuilder().number(1000).build(), repo);
prModel = new PullRequestModel(credentialStore, telemetry, repo, remote, prItem);
prItem.bodyHTML = '<p>Please merge thx</p>';
prModel = repo.createOrUpdatePullRequestModel(prItem);
getRepository = sinon.stub(pullRequestManager, 'createGitHubRepositoryFromOwnerName').resolves(repo);
getPreview = sinon.stub(repo, 'getPullRequestPreview').resolves(preview);
getRepositoryAccess = sinon.stub(pullRequestManager, 'getPullRequestRepositoryAccessAndMergeMethods').resolves({
Expand Down Expand Up @@ -987,6 +997,97 @@ describe('PullRequestOverview', function () {

previewLoadingTests(() => ({ model: prModel, preview, getPreview, getRepository, getRepositoryAccess, getAssignableUsers, openPanel, messages, webviewPanel }));

for (const bodyHTML of [undefined, '', ' ']) {
it(`loads missing description HTML before initialization (${JSON.stringify(bodyHTML)})`, async function () {
prModel.bodyHTML = bodyHTML;
let resolveDescription!: (description: PullRequestPreview) => void;
const getDescription = getPreview.returns(new Promise(resolve => resolveDescription = resolve));
const opening = openPanel();
await new Promise(resolve => setImmediate(resolve));
assert.strictEqual(messages.some(message => message.command === 'pr.initialize'), false);
sinon.assert.calledOnce(getDescription);
sinon.assert.calledWithExactly(getDescription, prModel.number);
resolveDescription({ ...preview, body: prModel.body, bodyHTML: '<p>Please merge thx</p>' });
await opening;
assert.strictEqual(messages.find(message => message.command === 'pr.initialize')?.pullrequest?.bodyHTML, prModel.bodyHTML);
});
}

it('initializes with description HTML parsed from a GitHub GraphQL response', async function () {
prModel.bodyHTML = undefined;
getPreview.restore();
const query = sinon.stub(repo, 'query').resolves({
loading: false, stale: false, networkStatus: NetworkStatus.ready,
data: { repository: { pullRequest: {
...preview, body: 'Actual GitHub Markdown', bodyHTML: '<p>Actual GitHub Markdown</p>',
author: null, baseRefName: 'main', headRefName: 'feature',
baseRepository: { owner: { login: remote.owner } }, headRepository: null,
} } },
});
await openPanel();
sinon.assert.calledWithMatch(query, { query: repo.schema.PullRequestPreview });
assert.strictEqual(messages.find(message => message.command === 'pr.initialize')?.pullrequest?.bodyHTML,
'<p>Actual GitHub Markdown</p>');
});

it('ignores description lookups that finish after the overview closes', async function () {
prModel.bodyHTML = undefined;
let resolveDescription!: (description: PullRequestPreview) => void;
getPreview.returns(new Promise(resolve => resolveDescription = resolve));
const opening = openPanel();
await new Promise(resolve => setImmediate(resolve));
webviewPanel.dispose();
resolveDescription({ ...preview, bodyHTML: '<p>Late description</p>' });
await opening;
assert.strictEqual(messages.some(message => message.command === 'pr.initialize'), false);
});

it('does not overwrite a newer overview when an older description lookup finishes', async function () {
prModel.bodyHTML = undefined;
let resolveDescription!: (description: PullRequestPreview) => void;
const getDescription = getPreview.returns(new Promise(resolve => resolveDescription = resolve));
const firstOpening = openPanel();
await new Promise(resolve => setImmediate(resolve));
sinon.assert.calledOnce(getDescription);
const cachedModel = repo.createOrUpdatePullRequestModel(prModel.item);
assert.strictEqual(cachedModel, prModel);
cachedModel.update({ ...cachedModel.item, body: 'New description', bodyHTML: '<p>New description</p>' });
const secondOpening = openPanel(cachedModel);
resolveDescription({ ...preview, body: 'Old description', bodyHTML: '<p>Old description</p>' });
await Promise.all([firstOpening, secondOpening]);
const initializations = messages.filter(message => message.command === 'pr.initialize');
assert.strictEqual(cachedModel.body, 'New description');
assert.strictEqual(cachedModel.bodyHTML, '<p>New description</p>');
assert.strictEqual(initializations.length, 1);
assert.strictEqual(initializations[0].pullrequest?.bodyHTML, '<p>New description</p>');
});

it('does not resolve a description that already has HTML', async function () {
const getDescription = getPreview;
await openPanel();
sinon.assert.notCalled(getDescription);
assert.strictEqual(messages.find(message => message.command === 'pr.initialize')?.pullrequest?.bodyHTML, prModel.bodyHTML);
});

it('does not resolve an empty description', async function () {
prModel.body = '';
prModel.bodyHTML = undefined;
const getDescription = getPreview;
await openPanel();
sinon.assert.notCalled(getDescription);
assert.ok(messages.some(message => message.command === 'pr.initialize'));
});

it('reports a description lookup failure instead of initializing a blank body', async function () {
prModel.bodyHTML = undefined;
getPreview.rejects(new Error('Description lookup failed'));
const showError = sinon.stub(vscode.window, 'showErrorMessage').resolves(undefined);
await openPanel();
assert.strictEqual(showError.firstCall.args[0], 'Error updating pull request description: Description lookup failed');
assert.strictEqual(messages.some(message => message.command === 'pr.initialize'), false);
});


describe('branch labels', function () {
const initialized = () => messages.find(message => message.command === 'pr.initialize')?.pullrequest;
const branchLabels = () => [initialized()?.base, initialized()?.head];
Expand Down Expand Up @@ -1620,6 +1721,7 @@ describe('PullRequestOverview', function () {
}

function stubModelServices(model: PullRequestModel) {
model.bodyHTML ??= '<p>Please merge thx</p>';
sinon.stub(model, 'canEdit').resolves(true);
sinon.stub(model, 'getReviewRequests').resolves([]);
const timeline = sinon.stub(model, 'getTimelineEvents').resolves([]);
Expand Down