Skip to content
Draft
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
5 changes: 4 additions & 1 deletion src/issues/issueHoverProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import { issueMarkdown } from '../github/markdownUtils';
import { RepositoriesManager } from '../github/repositoriesManager';
import { ISSUE_OR_URL_EXPRESSION, ParsedIssue, parseIssueExpressionOutput } from '../github/utils';

// Issue references in YAML are commonly written in string values, such as `- Fixed crash (#123)`.
const STRING_HOVER_LANGUAGE_IDS = ['yaml'];

export class IssueHoverProvider implements vscode.HoverProvider {
constructor(
private manager: RepositoriesManager,
Expand All @@ -28,7 +31,7 @@ export class IssueHoverProvider implements vscode.HoverProvider {
position: vscode.Position,
_token: vscode.CancellationToken,
): Promise<vscode.Hover | undefined> {
if (!(await shouldShowHover(document, position))) {
if (!(await shouldShowHover(document, position, STRING_HOVER_LANGUAGE_IDS))) {
return;
}

Expand Down
16 changes: 14 additions & 2 deletions src/issues/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -554,12 +554,24 @@ export async function isComment(document: vscode.TextDocument, position: vscode.
return true;
}

export async function shouldShowHover(document: vscode.TextDocument, position: vscode.Position): Promise<boolean> {
/**
* Hovers are shown anywhere in markdown and plaintext. In other languages they are only shown in comments,
* and additionally in strings for the languages in `stringLanguageIds`.
*/
export async function shouldShowHover(document: vscode.TextDocument, position: vscode.Position, stringLanguageIds: string[] = []): Promise<boolean> {
if (document.lineAt(position.line).range.end.character > 10000) {
return false;
}

return isComment(document, position);
if (document.languageId === 'markdown' || document.languageId === 'plaintext') {
return true;
}

const tokenInfo = await vscode.languages.getTokenInformationAtPosition(document, position);
if (tokenInfo.type === vscode.StandardTokenType.Comment) {
return true;
}
return tokenInfo.type === vscode.StandardTokenType.String && stringLanguageIds.includes(document.languageId);
}

export function getRootUriFromScmInputUri(uri: vscode.Uri): vscode.Uri | undefined {
Expand Down
59 changes: 57 additions & 2 deletions src/test/issues/issuesUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
*--------------------------------------------------------------------------------------------*/

import { default as assert } from 'assert';
import { createSandbox } from 'sinon';
import { createSandbox, SinonSandbox } from 'sinon';
import * as vscode from 'vscode';
import { getIssueOrURLExpression, ISSUE_OR_URL_EXPRESSION, parseIssueExpressionOutput } from '../../github/utils';
import { getUpstreamOrigin } from '../../issues/util';
import { getUpstreamOrigin, shouldShowHover } from '../../issues/util';
import { mockEnterpriseUris } from '../mocks/mockEnterpriseUris';
import { MockTextDocument } from '../mocks/mockTextDocument';

describe('Issues utilities', function () {
it('derives enterprise links from the upstream deployment of a configured instance', function () {
Expand Down Expand Up @@ -138,3 +139,57 @@ describe('Issues utilities', function () {
assert.strictEqual(enterpriseAgainstDefault, undefined);
});
});

describe('shouldShowHover', function () {
let sinon: SinonSandbox;

beforeEach(function () {
sinon = createSandbox();
});

afterEach(function () {
sinon.restore();
});

function stubTokenType(type: vscode.StandardTokenType) {
sinon.stub(vscode.languages, 'getTokenInformationAtPosition').callsFake(async (_document, position) => ({ type, range: new vscode.Range(position, position) }));
}

it('shows hovers anywhere in markdown and plaintext', async function () {
stubTokenType(vscode.StandardTokenType.Other);
for (const language of ['markdown', 'plaintext']) {
const document = new MockTextDocument(language, 'Fixes #123 thanks to @alexr00');
assert.strictEqual(await shouldShowHover(document, new vscode.Position(0, 8)), true, language);
assert.strictEqual(await shouldShowHover(document, new vscode.Position(0, 24)), true, language);
}
});

it('shows hovers in comments', async function () {
stubTokenType(vscode.StandardTokenType.Comment);
const document = new MockTextDocument('yaml', 'key: value # see #123');
assert.strictEqual(await shouldShowHover(document, new vscode.Position(0, 18)), true);
});

it('shows hovers in strings only for the given languages', async function () {
stubTokenType(vscode.StandardTokenType.String);
const yaml = new MockTextDocument('yaml', '- Fixed crash (#123)');
const position = new vscode.Position(0, 16);
assert.strictEqual(await shouldShowHover(yaml, position, ['yaml']), true);
assert.strictEqual(await shouldShowHover(yaml, position), false);

const sql = new MockTextDocument('sql', `SELECT 'Fixed crash (#123)';`);
assert.strictEqual(await shouldShowHover(sql, new vscode.Position(0, 23), ['yaml']), false);
});

it('does not show hovers outside of comments and strings', async function () {
stubTokenType(vscode.StandardTokenType.Other);
const document = new MockTextDocument('yaml', 'key: [GH-123]');
assert.strictEqual(await shouldShowHover(document, new vscode.Position(0, 5), ['yaml']), false);
});

it('does not show hovers on very long lines', async function () {
stubTokenType(vscode.StandardTokenType.Comment);
const document = new MockTextDocument('markdown', `Fixes #123 ${'a'.repeat(10000)}`);
assert.strictEqual(await shouldShowHover(document, new vscode.Position(0, 8)), false);
});
});
119 changes: 119 additions & 0 deletions src/test/mocks/mockTextDocument.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';

/**
* An in-memory, read-only text document with `\n` line endings. Unlike documents from
* `vscode.workspace.openTextDocument`, it isn't known to VS Code, so editor services
* (such as `vscode.languages.getTokenInformationAtPosition`) must be stubbed when used with it.
*/
export class MockTextDocument implements vscode.TextDocument {
readonly uri: vscode.Uri;
readonly fileName: string;
readonly isUntitled = true;
readonly encoding = 'utf8';
readonly version = 1;
readonly isDirty = false;
readonly isClosed = false;
readonly eol = vscode.EndOfLine.LF;
private readonly _lines: string[];

constructor(readonly languageId: string, private readonly _content: string) {
this._lines = _content.split('\n');
this.uri = vscode.Uri.from({ scheme: 'untitled', path: `mock.${languageId}` });
this.fileName = this.uri.path;
}

get lineCount(): number {
return this._lines.length;
}

async save(): Promise<boolean> {
return false;
}

lineAt(lineOrPosition: number | vscode.Position): vscode.TextLine {
const lineNumber = typeof lineOrPosition === 'number' ? lineOrPosition : lineOrPosition.line;
if (lineNumber < 0 || lineNumber >= this._lines.length) {
throw new Error(`Illegal line number ${lineNumber}`);
}
const text = this._lines[lineNumber];
const firstNonWhitespace = text.search(/\S/);
const firstNonWhitespaceCharacterIndex = firstNonWhitespace === -1 ? text.length : firstNonWhitespace;
const isLastLine = lineNumber === this._lines.length - 1;
return {
lineNumber,
text,
range: new vscode.Range(lineNumber, 0, lineNumber, text.length),
rangeIncludingLineBreak: isLastLine ? new vscode.Range(lineNumber, 0, lineNumber, text.length) : new vscode.Range(lineNumber, 0, lineNumber + 1, 0),
firstNonWhitespaceCharacterIndex,
isEmptyOrWhitespace: firstNonWhitespaceCharacterIndex === text.length,
};
}

offsetAt(position: vscode.Position): number {
const { line, character } = this.validatePosition(position);
let offset = 0;
for (let i = 0; i < line; i++) {
offset += this._lines[i].length + 1;
}
return offset + character;
}

positionAt(offset: number): vscode.Position {
let remaining = Math.max(0, Math.min(offset, this._content.length));
for (let line = 0; line < this._lines.length; line++) {
if (remaining <= this._lines[line].length) {
return new vscode.Position(line, remaining);
}
remaining -= this._lines[line].length + 1;
}
const lastLine = this._lines.length - 1;
return new vscode.Position(lastLine, this._lines[lastLine].length);
}

getText(range?: vscode.Range): string {
if (!range) {
return this._content;
}
const validRange = this.validateRange(range);
return this._content.substring(this.offsetAt(validRange.start), this.offsetAt(validRange.end));
}

getWordRangeAtPosition(position: vscode.Position, regex: RegExp = /\w+/g): vscode.Range | undefined {
const { line, character } = this.validatePosition(position);
const text = this._lines[line];
const globalRegex = new RegExp(regex.source, regex.flags.includes('g') ? regex.flags : `${regex.flags}g`);
let match: RegExpExecArray | null;
while ((match = globalRegex.exec(text))) {
const start = match.index;
const end = start + match[0].length;
if (start <= character && character <= end) {
return new vscode.Range(line, start, line, end);
}
if (match[0].length === 0) {
globalRegex.lastIndex++;
}
}
return undefined;
}

validateRange(range: vscode.Range): vscode.Range {
return new vscode.Range(this.validatePosition(range.start), this.validatePosition(range.end));
}

validatePosition(position: vscode.Position): vscode.Position {
if (position.line < 0) {
return new vscode.Position(0, 0);
}
if (position.line >= this._lines.length) {
const lastLine = this._lines.length - 1;
return new vscode.Position(lastLine, this._lines[lastLine].length);
}
const character = Math.max(0, Math.min(position.character, this._lines[position.line].length));
return new vscode.Position(position.line, character);
}
}
Loading