Repository navigation
Expand file tree
/
Copy pathdocumentLinkProvider.ts
More file actions
59 lines (51 loc) · 2.39 KB
/
Copy pathdocumentLinkProvider.ts
File metadata and controls
59 lines (51 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import * as fs from 'fs-extra';
import * as path from 'path';
import * as url from 'url';
import { CancellationToken, DocumentLink, DocumentLinkProvider, Position, Range, TextDocument, Uri } from 'vscode';
import * as Constants from '../common/constants';
import { getWorkspaceRootPath } from '../utils/workspaceUtility';
export class RequestBodyDocumentLinkProvider implements DocumentLinkProvider {
private _linkPattern = /^(\<(?:@(?:\w+)?)?\s+)(.+)(\s*)$/g;
public provideDocumentLinks(document: TextDocument, _token: CancellationToken): DocumentLink[] {
const results: DocumentLink[] = [];
const base = path.dirname(document.uri.toString());
const text = document.getText();
const lines: string[] = text.split(Constants.LineSplitterRegex);
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
let match: RegExpMatchArray | null;
if (match = this._linkPattern.exec(line)) {
const filePath = match[2];
const offset = match[1].length;
const linkStart = new Position(index, offset);
const linkEnd = new Position(index, offset + filePath.length);
results.push(new DocumentLink(
new Range(linkStart, linkEnd),
this.normalizeLink(document, filePath, base)
));
}
}
return results;
}
private normalizeLink(document: TextDocument, link: string, base: string): Uri {
let resourcePath: Uri;
if (path.isAbsolute(link)) {
resourcePath = Uri.file(link);
} else {
let rootPath = getWorkspaceRootPath();
if (rootPath) {
rootPath = rootPath.replace(/\/?$/, '/');
let resourcePathString = url.resolve(rootPath, link);
if (!fs.existsSync(resourcePathString)) {
base = base.replace(/\/?$/, '/');
resourcePathString = url.resolve(base, link);
}
resourcePath = Uri.parse(resourcePathString);
} else {
base = base.replace(/\/?$/, '/');
resourcePath = Uri.parse(url.resolve(base, link));
}
}
return Uri.parse(`command:rest-client._openDocumentLink?${encodeURIComponent(JSON.stringify({ path: resourcePath }))}`);
}
}