-
Notifications
You must be signed in to change notification settings - Fork 724
Expand file tree
/
Copy pathuri.ts
More file actions
463 lines (410 loc) · 12.2 KB
/
uri.ts
File metadata and controls
463 lines (410 loc) · 12.2 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { Buffer } from 'buffer';
import * as pathUtils from 'path';
import fetch from 'cross-fetch';
import * as vscode from 'vscode';
import { Repository } from '../api/api';
import { IAccount, ITeam, reviewerId } from '../github/interface';
import { PullRequestModel } from '../github/pullRequestModel';
import { GitChangeType } from './file';
import Logger from './logger';
import { TemporaryState } from './temporaryState';
export interface ReviewUriParams {
path: string;
ref?: string;
commit?: string;
base: boolean;
isOutdated: boolean;
rootPath: string;
}
export function fromReviewUri(query: string): ReviewUriParams {
return JSON.parse(query);
}
export interface PRUriParams {
baseCommit: string;
headCommit: string;
isBase: boolean;
fileName: string;
prNumber: number;
status: GitChangeType;
remoteName: string;
previousFileName?: string;
}
export function fromPRUri(uri: vscode.Uri): PRUriParams | undefined {
if (uri.query === '') {
return undefined;
}
try {
return JSON.parse(uri.query) as PRUriParams;
} catch (e) { }
}
export interface PRNodeUriParams {
prIdentifier: string
}
export function fromPRNodeUri(uri: vscode.Uri): PRNodeUriParams | undefined {
if (uri.query === '') {
return undefined;
}
try {
return JSON.parse(uri.query) as PRNodeUriParams;
} catch (e) { }
}
export interface GitHubUriParams {
fileName: string;
branch: string;
owner?: string;
isEmpty?: boolean;
}
export function fromGitHubURI(uri: vscode.Uri): GitHubUriParams | undefined {
if (uri.query === '') {
return undefined;
}
try {
return JSON.parse(uri.query) as GitHubUriParams;
} catch (e) { }
}
export function toGitHubUri(fileUri: vscode.Uri, scheme: Schemes.GithubPr | Schemes.GitPr, params: GitHubUriParams): vscode.Uri {
return fileUri.with({
scheme,
query: JSON.stringify(params)
});
}
export interface GitUriOptions {
replaceFileExtension?: boolean;
submoduleOf?: string;
base: boolean;
}
const ImageMimetypes = ['image/png', 'image/gif', 'image/jpeg', 'image/webp', 'image/tiff', 'image/bmp'];
// Known media types that VS Code can handle: https://github.com/microsoft/vscode/blob/a64e8e5673a44e5b9c2d493666bde684bd5a135c/src/vs/base/common/mime.ts#L33-L84
export const KnownMediaExtensions = [
'.aac',
'.avi',
'.bmp',
'.flv',
'.gif',
'.ico',
'.jpe',
'.jpeg',
'.jpg',
'.m1v',
'.m2a',
'.m2v',
'.m3a',
'.mid',
'.midi',
'.mk3d',
'.mks',
'.mkv',
'.mov',
'.movie',
'.mp2',
'.mp2a',
'.mp3',
'.mp4',
'.mp4a',
'.mp4v',
'.mpe',
'.mpeg',
'.mpg',
'.mpg4',
'.mpga',
'.oga',
'.ogg',
'.opus',
'.ogv',
'.png',
'.psd',
'.qt',
'.spx',
'.svg',
'.tga',
'.tif',
'.tiff',
'.wav',
'.webm',
'.webp',
'.wma',
'.wmv',
'.woff'
];
// a 1x1 pixel transparent gif, from http://png-pixel.com/
export const EMPTY_IMAGE_URI = vscode.Uri.parse(
`data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==`,
);
export async function asTempStorageURI(uri: vscode.Uri, repository: Repository): Promise<vscode.Uri | undefined> {
try {
const { commit, baseCommit, headCommit, isBase, path }: { commit: string, baseCommit: string, headCommit: string, isBase: string, path: string } = JSON.parse(uri.query);
const ext = pathUtils.extname(path);
if (!KnownMediaExtensions.includes(ext)) {
return;
}
const ref = uri.scheme === Schemes.Review ? commit : isBase ? baseCommit : headCommit;
const absolutePath = pathUtils.join(repository.rootUri.fsPath, path).replace(/\\/g, '/');
const { object } = await repository.getObjectDetails(ref, absolutePath);
const { mimetype } = await repository.detectObjectType(object);
if (mimetype === 'text/plain') {
return;
}
if (ImageMimetypes.indexOf(mimetype) > -1) {
const contents = await repository.buffer(ref, absolutePath);
return TemporaryState.write(pathUtils.dirname(path), pathUtils.basename(path), contents);
}
} catch (err) {
return;
}
}
export namespace DataUri {
const iconsFolder = 'userIcons';
function iconFilename(user: IAccount | ITeam): string {
return `${reviewerId(user)}.jpg`;
}
function cacheLocation(context: vscode.ExtensionContext): vscode.Uri {
return vscode.Uri.joinPath(context.globalStorageUri, iconsFolder);
}
function fileCacheUri(context: vscode.ExtensionContext, user: IAccount | ITeam): vscode.Uri {
return vscode.Uri.joinPath(cacheLocation(context), iconFilename(user));
}
function cacheLogUri(context: vscode.ExtensionContext): vscode.Uri {
return vscode.Uri.joinPath(cacheLocation(context), 'cache.log');
}
async function writeAvatarToCache(context: vscode.ExtensionContext, user: IAccount | ITeam, contents: Uint8Array): Promise<vscode.Uri> {
await vscode.workspace.fs.createDirectory(cacheLocation(context));
const file = fileCacheUri(context, user);
await vscode.workspace.fs.writeFile(file, contents);
return file;
}
async function readAvatarFromCache(context: vscode.ExtensionContext, user: IAccount | ITeam): Promise<Uint8Array | undefined> {
try {
const file = fileCacheUri(context, user);
return vscode.workspace.fs.readFile(file);
} catch (e) {
return;
}
}
export function asImageDataURI(contents: Buffer): vscode.Uri {
return vscode.Uri.parse(
`data:image/svg+xml;size:${contents.byteLength};base64,${contents.toString('base64')}`
);
}
export async function avatarCirclesAsImageDataUris(context: vscode.ExtensionContext, users: (IAccount | ITeam)[], height: number, width: number, localOnly?: boolean): Promise<(vscode.Uri | undefined)[]> {
let cacheLogOrder: string[];
const cacheLog = cacheLogUri(context);
try {
const log = await vscode.workspace.fs.readFile(cacheLog);
cacheLogOrder = JSON.parse(log.toString());
} catch (e) {
cacheLogOrder = [];
}
const startingCacheSize = cacheLogOrder.length;
const results = await Promise.all(users.map(async (user) => {
const imageSourceUrl = user.avatarUrl;
if (imageSourceUrl === undefined) {
return undefined;
}
let innerImageContents: Buffer | undefined;
let cacheMiss: boolean = false;
try {
const fileContents = await readAvatarFromCache(context, user);
if (!fileContents) {
throw new Error('Temporary state not initialized');
}
innerImageContents = Buffer.from(fileContents);
} catch (e) {
if (localOnly) {
return;
}
cacheMiss = true;
const doFetch = async () => {
const response = await fetch(imageSourceUrl.toString());
const buffer = await response.arrayBuffer();
await writeAvatarToCache(context, user, new Uint8Array(buffer));
innerImageContents = Buffer.from(buffer);
};
try {
await doFetch();
} catch (e) {
// We retry once.
await doFetch();
}
}
if (!innerImageContents) {
return undefined;
}
if (cacheMiss) {
const icon = iconFilename(user);
cacheLogOrder.push(icon);
}
const innerImageEncoded = `data:image/jpeg;size:${innerImageContents.byteLength};base64,${innerImageContents.toString('base64')}`;
const contentsString = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image href="${innerImageEncoded}" width="${width}" height="${height}" style="clip-path: inset(0 0 0 0 round 50%);"/>
</svg>`;
const contents = Buffer.from(contentsString);
const finalDataUri = asImageDataURI(contents);
return finalDataUri;
}));
const maxCacheSize = Math.max(users.length, 200);
if (cacheLogOrder.length > startingCacheSize && startingCacheSize > 0 && cacheLogOrder.length > maxCacheSize) {
// The cache is getting big, we should clean it up.
const toDelete = cacheLogOrder.splice(0, 50);
await Promise.all(toDelete.map(async (id) => {
try {
await vscode.workspace.fs.delete(vscode.Uri.joinPath(cacheLocation(context), id));
} catch (e) {
Logger.error(`Failed to delete avatar from cache: ${e}`);
}
}));
}
await vscode.workspace.fs.writeFile(cacheLog, Buffer.from(JSON.stringify(cacheLogOrder)));
return results;
}
}
export function toReviewUri(
uri: vscode.Uri,
filePath: string | undefined,
ref: string | undefined,
commit: string,
isOutdated: boolean,
options: GitUriOptions,
rootUri: vscode.Uri,
): vscode.Uri {
const params: ReviewUriParams = {
path: filePath ? filePath : uri.path,
ref,
commit: commit,
base: options.base,
isOutdated,
rootPath: rootUri.path,
};
let path = uri.path;
if (options.replaceFileExtension) {
path = `${path}.git`;
}
return uri.with({
scheme: Schemes.Review,
path,
query: JSON.stringify(params),
});
}
export interface FileChangeNodeUriParams {
prNumber: number;
fileName: string;
previousFileName?: string;
status?: GitChangeType;
}
export function toResourceUri(uri: vscode.Uri, prNumber: number, fileName: string, status: GitChangeType, previousFileName?: string) {
const params: FileChangeNodeUriParams = {
prNumber,
fileName,
status,
previousFileName
};
return uri.with({
scheme: Schemes.FileChange,
query: JSON.stringify(params),
});
}
export function fromFileChangeNodeUri(uri: vscode.Uri): FileChangeNodeUriParams | undefined {
if (uri.query === '') {
return undefined;
}
try {
return JSON.parse(uri.query) as FileChangeNodeUriParams;
} catch (e) { }
}
export function toPRUri(
uri: vscode.Uri,
pullRequestModel: PullRequestModel,
baseCommit: string,
headCommit: string,
fileName: string,
base: boolean,
status: GitChangeType,
previousFileName?: string
): vscode.Uri {
const params: PRUriParams = {
baseCommit: baseCommit,
headCommit: headCommit,
isBase: base,
fileName: fileName,
prNumber: pullRequestModel.number,
status: status,
remoteName: pullRequestModel.githubRepository.remote.remoteName,
previousFileName
};
const path = uri.path;
return uri.with({
scheme: Schemes.Pr,
path,
query: JSON.stringify(params),
});
}
export function createPRNodeIdentifier(pullRequest: PullRequestModel | { remote: string, prNumber: number } | string) {
let identifier: string;
if (pullRequest instanceof PullRequestModel) {
identifier = `${pullRequest.remote.url}:${pullRequest.number}`;
} else if (typeof pullRequest === 'string') {
identifier = pullRequest;
} else {
identifier = `${pullRequest.remote}:${pullRequest.prNumber}`;
}
return identifier;
}
export function createPRNodeUri(
pullRequest: PullRequestModel | { remote: string, prNumber: number } | string
): vscode.Uri {
const identifier = createPRNodeIdentifier(pullRequest);
const params: PRNodeUriParams = {
prIdentifier: identifier,
};
const uri = vscode.Uri.parse(`PRNode:${identifier}`);
return uri.with({
scheme: Schemes.PRNode,
query: JSON.stringify(params)
});
}
export interface NotificationUriParams {
key: string;
}
export function toNotificationUri(params: NotificationUriParams) {
return vscode.Uri.from({ scheme: Schemes.Notification, path: params.key });
}
export function fromNotificationUri(uri: vscode.Uri): NotificationUriParams | undefined {
if (uri.scheme !== Schemes.Notification) {
return;
}
try {
return {
key: uri.path,
};
} catch (e) { }
}
export enum Schemes {
File = 'file',
Review = 'review', // File content for a checked out PR
Pr = 'pr', // File content from GitHub for non-checkout PR
PRNode = 'prnode',
FileChange = 'filechange', // Tree items, for decorations
GithubPr = 'githubpr', // File content from GitHub in create flow
GitPr = 'gitpr', // File content from git in create flow
VscodeVfs = 'vscode-vfs', // Remote Repository
Comment = 'comment', // Comments from the VS Code comment widget
MergeOutput = 'merge-output', // Merge output
Notification = 'notification' // Notification tree items in the notification view
}
export function resolvePath(from: vscode.Uri, to: string) {
if (from.scheme === Schemes.File) {
return pathUtils.resolve(from.fsPath, to);
} else {
return pathUtils.posix.resolve(from.path, to);
}
}
class UriEventHandler extends vscode.EventEmitter<vscode.Uri> implements vscode.UriHandler {
public handleUri(uri: vscode.Uri) {
this.fire(uri);
}
}
export const handler = new UriEventHandler();